import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestSwingListeners1 {
private static int cnt1;
private static int cnt2;
public static void main(String[] args) {
JFrame fr1 = new JFrame("Swing Window");
Container cp;
JButton bt1;
JButton bt2;
cnt1 = 0;
cnt2 = 0;
String scr = null;
String wnr = null;
JButton btOK, btCancel;
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr1.setSize(300, 200);
fr1.setResizable(false);
cp = fr1.getContentPane();
cp.setLayout(new GridLayout(5,1));
btOK = new JButton("AC Milan");
btCancel = new JButton("Real Madrid");
JLabel lbl1 = new JLabel("Result: " + cnt1 + "X" + cnt2);
JLabel lbl2 = new JLabel("Last Scorer: " + scr);
JLabel lbl3 = new JLabel("Winner: " + wnr);
cp.add(btOK);
cp.add(btCancel);
cp.add(lbl1);
cp.add(lbl2);
cp.add(lbl3);
//lbl1.setText(displayText);
btOK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
//String displayText = "" + 1;
cnt1++;
}
});
btCancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cnt2++;
}
});
fr1.show();
}
当我按下btOK
按钮时,我希望cnt1
递增并与btCancel
相同 - 按下cnt2
时增加{{1}}。
怎么做?
答案 0 :(得分:2)
您需要使用.setText()
更新标签,如:
btOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cnt1++;
lbl1.setText("Result: " + cnt1 + " X " + cnt2);
}
}
你需要改变:
JLabel lbl1 = new JLabel("Result: " + cnt1 + "X" + cnt2);
到
final JLabel lbl1 = new JLabel("Result: " + cnt1 + "X" + cnt2);
因此可以从作为内部类的ActionListener访问它。
答案 1 :(得分:2)
您需要注册ActionListener
Read More
答案 2 :(得分:1)
public class TestSwingListeners1 implements ActionListener
{
// ...
btOK = new JButton("AC Milan");
btOK.setActionCommand("OK");
btOKaddActionListener(this);
btCancel = new JButton("Real Madrid");
btCancel.setActionCommand("Cancel");
btCancel.addActionListener(this);
// ...
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("OK"))
{
lbl1.setText("Result: " + ++cnt1 + "X" + cnt2);
}
else if(e.getActionCommand().equals("Cancel"))
{
lbl1.setText("Result: " + cnt1 + "X" + ++cnt2);
}
}
}