注:我的英語不是最好的所以請不要介意太多的語法錯誤。java;如何獲取Action Listener之外的變量?
嘿那裏,java初學者在這裏,無論如何,我編寫了我的CPS測試程序,就像第一個小程序一樣。不管怎麼說,這個問題可能已經問過,但我 需要得到一個變量的一個外面的ActionListener代碼:
public static void startB() {
Font f = new Font(null, Font.BOLD , 0);
Font size = f.deriveFont(20f);
JLabel text = new JLabel("");
text.setPreferredSize(new Dimension(250,250));
text.setFont(size);
JButton b = new JButton();
JFrame cps = new JFrame("CLICK");
cps.setPreferredSize(new Dimension(400,400));
cps.setLocationRelativeTo(null);
cps.setLayout(new FlowLayout());
b.setText("<html> CLICK ME <br> As much as you can! <html> ");
cps.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cps.getContentPane().add(b , BorderLayout.CENTER);
cps.getContentPane().add(text, BorderLayout.CENTER);
cps.pack();
cps.setVisible(true);
text.setText("<html> Starting in... <br> 3<html>");
try {
TimeUnit.SECONDS.sleep((long)1.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText("<html> Starting in... <br> 2<html>");
try {
TimeUnit.SECONDS.sleep((long)1.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText("<html> Starting in... <br> 1<html>");
try {
TimeUnit.SECONDS.sleep((long)1.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText("<html> CLICK! <html>");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double clicks = 0;
clicks++;
// How to get Clicks variable out of the actionListener?
}
});
try {
TimeUnit.SECONDS.sleep((long)10.0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//I need get the Clicks Variable to here.
}
如果你能幫助我請的帖子作出迴應。謝謝。
@davidxxx我剛剛提供了一個問題的答案,並已經提到,它不是最好的方式。 – dpr
對不起,我不好讀。我明白了相反的意思。作爲這種警告的替代方法,這很好。 – davidxxx