我正在使用 java swing 并嘗試使用新文本作為引數,但我不確定如何使用,還有一個事實是我有 "});" 這完全搞砸了但它有效,我嘗試修復它但它不起作用
這段代碼在我的主里面
public String newText = "";
a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFrame popup = new JFrame("Choose...");
popup.setSize(250,250);
popup.setLayout(null);
popup.setVisible(true);
JButton o=new JButton("o");
o.setBounds(25,75,100,100);
popup.add(o);
o.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae, String newText){
newText = "O";
}
});
JButton x=new JButton("x");
x.setBounds(125,75,100,100);
popup.add(x);
if (!newText.equals(""))
a.setText(newText);
}
});
uj5u.com熱心網友回復:
我試過
newText用作引數
這里?
public void actionPerformed(ActionEvent ae, String newText){
這不是有效代碼。ActionListener是一個介面;介面是必須遵守的契約。您不能簡單地向現有方法簽名添加變數。
假設你想修改按鈕文本,你可以這樣做
public class Main {
public String newText;
public static void main(String[] args) {
new Main().run();
}
public void run() {
System.out.printf("before: newText = %s%n", newText);
final JButton o = new JButton("o");
// ...
o.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
Main.this.newText = "O"; // Sets the field
System.out.printf("action: newText = %s%n", Main.this.newText);
o.setText(Main.this.newText);
}
});
System.out.printf("actionListener set : newText = %s%n", newText);
}
}
但是,嘗試newText.equals在動作偵聽器之外使用發生在不同的執行緒上,這意味著代碼不會“從上到下”運行。例如,變數不是按照代碼讀取的執行順序“設定”的。添加了列印陳述句來顯示這一點
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345306.html
上一篇:反射而不是工廠模式?
