我正在开发一个程序。我创建了一个 JFrame,其中包含一堆面板、按钮、标签和文本字段。由于某种原因,JFrame 出现了,但里面什么也没有。代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
setVisible(true);
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
optionsPanel.add(rect);
optionsPanel.add(oval);
optionsPanel.add(tri);
optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
最佳答案
您的
JComponents
未初始化,您已将
JComponents
添加到已可见的JFrame
中,您必须将代码行
setVisible(true);
移动到构造函数的末尾,Swing GUI 应在 Initial Thread 上打包
关于java - 图形元素不会出现在 JFrame (Java) 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20741712/