我已经构建了一个基于 Swing 的 GUI,它构建成功。但运行后,它只显示一个空白的白色框架,上面没有任何文本、按钮。
我已经检查了 GUI 元素是否已添加到面板中 (
myPanel.add(bTest, "Card1");
)。另外 $$$setupUI$$$();
应该在构造函数之后执行。
代码:
package voc;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GUI extends JFrame {
private JPanel myPanel;
private JButton bTest;
private JTextArea tEnterTranslation;
public GUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
bTest.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
}
});
}
public static void create() {
GUI gui = new GUI();
}
public static void main(String[] args) {
create();
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
myPanel = new JPanel();
myPanel.setLayout(new CardLayout(0, 0));
myPanel.setMaximumSize(new Dimension(500, 500));
myPanel.setMinimumSize(new Dimension(500, 500));
myPanel.setPreferredSize(new Dimension(500, 500));
myPanel.setBorder(BorderFactory.createTitledBorder(null, "voc", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font(myPanel.getFont().getName(), myPanel.getFont().getStyle(), myPanel.getFont().getSize()), new Color(-4497096)));
bTest = new JButton();
bTest.setMinimumSize(new Dimension(10, 20));
bTest.setText("Button");
myPanel.add(bTest, "Card1");
tEnterTranslation = new JTextArea();
tEnterTranslation.setMinimumSize(new Dimension(20, 15));
tEnterTranslation.setPreferredSize(new Dimension(20, 15));
tEnterTranslation.setText("");
myPanel.add(tEnterTranslation, "Card2");
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return myPanel;
}
}
您忘记将
JPanel
添加到您的 JFrame
的 contentPane()
public GUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(myPanel); <--------------------------------- HERE
this.setVisible(true);
bTest.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
}
});
}
如果我是你,我也会使用
JFrame#setSize(Dimension)
,因为你的 JFrame
现在将以最小尺寸显示。