[英]can't add an ActionListener to add a Component
Supposing that I want to click a button, then a JLabel/JTextArea/... will show in the GUI, how to finish the job? 假设我想单击一个按钮,那么JLabel / JTextArea / ...将显示在GUI中,如何完成这项工作?
Example code: 示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyJFrame extends JFrame {
public MyJFrame() {
JButton jButton = new JButton();
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
add(new JLabel("xxxxx"), BorderLayout.SOUTH);
}
});
add(jButton, BorderLayout.CENTER);
}
public static void main(String[] args) {
MyJFrame myJFrame = new MyJFrame();
myJFrame.pack();
myJFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
myJFrame.setVisible(true);
myJFrame.setLocationRelativeTo(null);
}
}
My code has something wrong. 我的代码有问题。 After I clicked the button, there is no JLabel show up.
单击按钮后,没有显示JLabel。
update: 更新:
Could anyone tell me what if I want to solve my problem from java official information, where should I search? 谁能告诉我要从Java官方信息解决问题的方法,我应该在哪里搜索? It seems JAVA tutorial or API have nothing relating with my question..
看来JAVA教程或API与我的问题无关。
You should notify the frame that its content has changed ( revalidate()
), and to repaint itself ( repaint()
) : 您应该通知框架其内容已更改(
revalidate()
),并重新绘制自身( repaint()
):
public void actionPerformed(ActionEvent e) {
add(new JLabel("xxxxx"), BorderLayout.SOUTH);
revalidate();
repaint();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.