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

标签 java swing jtextarea

我正在设计一个简单的 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/

相关文章:

java - 当从文本字段单击输入时,执行与按钮执行的操作相同的代码

java - 如何在新文本区域设置光标?

java - 基地址默认为 localhost

java - Java类Stack继承自Vector有哪些负面影响?

java - 覆盖单个组件的 Swing 外观

java - 我如何在 Java 的不同 JPanel 中绘制随机形状

java - 按 JRadiobutton 卡住 GUI

java - swing - 为什么要创建两个单独的盒子

java - 为什么带有 arg 的构造函数取消定义默认构造函数?

java - 条形图 JFreeChart 中的范围