gpt4 book ai didi

java - 按钮不显示文本区域中的文本

转载 作者:行者123 更新时间:2023-12-01 18:37:26 26 4
gpt4 key购买 nike

我正在设计一个简单的 GUI(在 Eclipse 中使用 WindowBuilder Pro),仅在按下按钮后在 textArea 中显示“Hello World”(测试)。

/image/PbYo8.jpg

但是,当我按下按钮时,它没有显示在文本区域中!有人可以调整代码或者至少告诉我该怎么做吗?

public class TextA {

private JFrame frame;


/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TextA window = new TextA();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public TextA() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JTextArea textArea = new JTextArea();
textArea.setBounds(113, 44, 226, 96);
frame.getContentPane().add(textArea);

JButton btnTesting = new JButton("Testing");
btnTesting.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

JTextArea textArea = new JTextArea();
textArea.setText("Hello World!");


}
});
btnTesting.setBounds(168, 167, 117, 29);
frame.getContentPane().add(btnTesting);
}
}

最佳答案

将您的代码更改为类似这样的内容。

 final JTextArea textArea = new JTextArea();
frame.getContentPane().add(textArea);
btnTesting.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.setText("Hello World!");
}
});

您正在 actionListener 内创建一个新实例,您希望引用要添加到框架中的对象。正如 @AndrewThompson 总是建议不要使用 null 布局原因:

Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.

关于java - 按钮不显示文本区域中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21316979/

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