我有一个被调用 4 次的方法。该方法返回一个 JPanel,其中有一个 JButton。我希望当我单击按钮1时打印1,按钮2时打印2,依此类推。现在,当我单击任何按钮时,它都会打印 4 。就像该方法被调用 4 次一样, count = 4 并且每个按钮都有 4 。我该如何解决这个问题?
private int count=0;
private JPanel createPanel(){
count++;
JPanel app = new JPanel(true);
app.setLayout(new GridLayout(1,1);
app.setPreferredSize(new Dimension(width,dHeight));
JButton btn = createButton("Click Me");
buttonStyle(btn);
btn.addActionListener(e -> this.doStuff(count));
app.add(btn);
return app;
}
private void doStuff(int t){
System.out.println(t);
}
最佳答案
当您说调用 createPanel()
4 次时,您的计数器将增加 4 倍。所有 doStuff()
调用都会传递变量 count
,该变量是您的类的成员,并由所有其他成员(例如 doStuff()
)共享。 count
之前增加了 4 倍,因此为 4。因此每个按钮都会打印出 4。
快速修复:
private JPanel createPanel(){
int copyCounter = count; // Copy the counter
count++;
JPanel app = new JPanel(true);
app.setLayout(new GridLayout(1,1);
app.setPreferredSize(new Dimension(width,dHeight));
JButton btn = createButton("Click Me");
buttonStyle(btn);
btn.addActionListener(e -> this.doStuff(copyCounter)); // Use copy here
app.add(btn);
return app;
}
通过执行此操作,您将在方法中创建计数器的副本,该值不会因将来调用 createPanel()
而增加。
关于java - 单击 JButton 时打印特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117581/