gpt4 book ai didi

java - 为什么我的 showMessageDialog 显示两次?

转载 作者:行者123 更新时间:2023-12-02 11:18:57 25 4
gpt4 key购买 nike

我正在开发一个简单的计数器 Swing 应用程序。我试图做到这一点,以便当您单击该复选框时,它将保留在顶部并显示一个消息对话框“在顶部”或“不在顶部”。

但是,当我在编译和运行后单击该复选框时,两条消息都会显示,并且在两条消息上单击“确定”后,该复选框甚至未启用。如果我删除 showMessageDialog,它仍然可以正常工作,但我想学习如何正确实现它。

提前谢谢您。以下是该程序的所有代码:

public Class Counter {

JFrame frame;
JPanel panel;
JButton button, clear;
JTextField textC;
JLabel label;
JCheckBox cbox;

boolean topC = false;
int icount = 0;
String scount;
String topStatus = "";

public Counter() {
gui();
setActions();
}

public void gui() {

frame = new JFrame("Counter Program");
panel = new JPanel();
label = new JLabel("Counter");
textC = new JTextField();
textC.setPreferredSize(new Dimension(72,28));
textC.setEditable(false);

button = new JButton("Click");
clear = new JButton("Clear");
cbox = new JCheckBox("Top");

frame.setSize(350,80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);

panel.add(label);
panel.add(textC);
panel.add(button);
panel.add(clear);
panel.add(cbox);

frame.setVisible(true);

}

public void setActions() {

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

icount++;
scount = Integer.toString(icount);
textC.setText(scount);

}

});

clear.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

icount = 0;
textC.setText("");

}

});


cbox.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

topC = !topC;
if (topC) {
topStatus = "Top";
}
else topStatus = "Not Top";

frame.setAlwaysOnTop(topC);
JOptionPane.showMessageDialog(frame, topStatus, "Top Setting", 1);

}

});

}

public static void main(String[]args) {
new Counter();
}
}

最佳答案

ItemListener 生成两个事件,一个用于选择,一个用于取消选择(反之亦然)。阅读 Swing 教程中关于 How to Write an ItemListener 的部分如果您确实想使用 ItemListener,请获取更多信息和工作示例。

否则,请使用 ActionListener 来代替,它只会生成一个事件。

关于java - 为什么我的 showMessageDialog 显示两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50071180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com