【发布时间】:2017-02-06 15:02:37
【问题描述】:
我使用 Eclipse 中的 WindowBuilder 构建了一个 Java-Swing GUI。但是当我尝试使用 .add() 和 .revalidate() 添加新组件时,没有任何反应。
如果有人可以帮助解决这个问题,我真的很感激。
package Frame;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
public class TestFrame {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame window = new TestFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestFrame() {
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);
JButton btnSampleButton = new JButton("Sample Button");
btnSampleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.add(new JButton("BTN"));
frame.revalidate();
frame.repaint();
}
});
frame.getContentPane().setLayout(null);
btnSampleButton.setBounds(110, 126, 185, 112);
frame.getContentPane().add(btnSampleButton);
}
}
【问题讨论】:
-
请将您的代码以SSCCE 的形式发布,以便我们查看问题所在。
-
好的,贴出我的代码
-
1) Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2) 在 GUI 可见后添加组件需要一些技巧。与其学习这些技巧,不如使用
CardLayout.. -
.. 如this answer 所示。这样,新组件的大小用于计算 GUI 的首选大小。在其中一张卡片中,使用空白面板。另一个是按钮。
标签: java swing user-interface windowbuilder