gpt4 book ai didi

java - 单击某个按钮时从 JPanel 中删除文本

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

我正在尝试为我正在开发的基于文本的冒险游戏创建一个 GUI。我需要让它做的事情是,当单击按钮“jButton3”时,它将删除“jText1”的文本。我尝试添加一个 ItemListener,但我似乎无法弄清楚。代码如下。为了简单起见,我省略了所有导入以及包名称,只需知道当我尝试运行此程序时不会出现任何错误。

我搜索了与我的主题相关的其他帖子,但找不到我要找的内容,其中大多数都是关于将 TextField 中的文本替换为 JLabel

public class DemoGUI extends javax.swing.JFrame {
public JLabel jLabel1;
public JTextField jText1;
public JButton jButton1;
public JButton jButton2;
public JButton jButton3;
String string1;

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DemoGUI inst = new DemoGUI();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public DemoGUI() {
super();
initGUI();
}
private void removeTextWhenClicked(JButton btn, ItemEvent ev) {
if(ev.getStateChange() == ItemEvent.ITEM_STATE_CHANGED) {
jText1.setText("");
}
}

public void initGUI() {
try {
FlowLayout thisLayout = new FlowLayout();
getContentPane().setLayout(thisLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);

jLabel1 = new JLabel("Center", SwingConstants.CENTER);
getContentPane().add(jLabel1);
jLabel1.setPreferredSize(new Dimension(320, 250));
jLabel1.setText(string1);
jLabel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));

jButton1 = new JButton();
getContentPane().add(jButton1);
jButton1.setPreferredSize(new Dimension(100, 50));
jButton1.setText("Map");

jButton2 = new JButton();
getContentPane().add(jButton2);
jButton2.setPreferredSize(new Dimension(100, 50));
jButton2.setText("Inventory");

jText1 = new JTextField();
getContentPane().add(jText1);
jText1.setPreferredSize(new Dimension(320, 100));
jText1.setBorder(BorderFactory.createLineBorder(Color.BLACK));

jButton3 = new JButton();
getContentPane().add(jButton3);
jButton3.setPreferredSize(new Dimension(100, 40));
jButton3.setText("Submit");
jButton3.addItemListener(ev -> removeTextWhenClicked(jButton3, ev));

pack();
this.setSize(350, 500);
} catch (Exception e) {
e.printStackTrace();
}
}

}

最佳答案

不要使用addItemListener,而是使用addActionListener

 jButton3.addActionListener(new ActionListener(){  
public void actionPerformed(ActionEvent e){

}
});

您可以在 Java: What's the difference between ActionEvent and ItemEvent on a JRadioButton? 找到差异

ItemListeners are notified when ever the state of the button ischanged, whether through a user interacting with the button orprogrammatically (via the setSelected method).

ActionListeners will be called when a user interacts with the button

关于java - 单击某个按钮时从 JPanel 中删除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49912751/

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