我一直在尝试将按钮的网格布局添加到 jpanel 上,但是当我运行代码时,jpanel 上什么也没有显示。
公共类 MyFrame 扩展 JFrame{
public static final int WIDTH = 800;
public static final int HEIGHT = 900;
MyFrame() {
this.setTitle("Percolation Simulation");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(WIDTH, HEIGHT);
this.setLayout(null);
this.setVisible(true);
JPanel mainPanel = new JPanel();
mainPanel.setBounds(0, 0, WIDTH, 600);
mainPanel.setBackground(Color.red);
mainPanel.setLayout(new GridLayout());
this.add(mainPanel);
mainPanel.add(new JButton());
mainPanel.add(new JButton());
mainPanel.add(new JButton());
mainPanel.setVisible(true);
}
}
null
布局,它们对你没有帮助this.setVisible(true)
无关紧要,默认情况下 Swing 组件是可见的(基于窗口的类除外)this.setVisible
作为最后一条语句,否则您需要 revalidate
和 repaint
已更改的容器,以触发新的布局和绘画过程。size - window decoration insets
,这可能会给您带来问题。最好设置内容的首选大小(或者让布局管理器完成他们的工作)和pack
它周围的窗口import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MyFrame();
}
});
}
public class MyFrame extends JFrame {
public static final int WIDTH = 800;
public static final int HEIGHT = 900;
MyFrame() {
this.setTitle("Percolation Simulation");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(MyFrame.WIDTH, MyFrame.HEIGHT);
}
};
mainPanel.setBackground(Color.red);
mainPanel.setLayout(new GridLayout());
mainPanel.add(new JButton(" "));
mainPanel.add(new JButton(" "));
mainPanel.add(new JButton(" "));
this.add(mainPanel);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
}
public class MyFrame{
public static final int WIDTH = 800;
public static final int HEIGHT = 900;
MyFrame() {
this.setTitle("Percolation Simulation");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(WIDTH, HEIGHT);
this.setLayout(null);
JPanel mainPanel = new JPanel();
mainPanel.setBounds(0, 0, WIDTH, 600);
mainPanel.setBackground(Color.red);
mainPanel.setLayout(new GridLayout(1,3));
mainPanel.add(new JButton());
mainPanel.add(new JButton());
mainPanel.add(new JButton());
// the JFrame is this
this.getContentPane().add(mainpanel); // add like this to a Frame or Window
this.setVisible(true);
this.setIgnoreRepaint(false);
}//end of constructor
// now progam entry point
public static void main(String[] args){ // always written this way
new MyFrame(); // recursive call to itself
}
}// end of class