Panel controlPanel = new Panel ();
JPanel chatPanel = new JPanel();
JPanel buttomsPanel = new JPanel();
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout(10));
Panel panel = new Panel();
panel.setBackground(Color.DARK_GRAY);
panel.setSize(700,700);
GridLayout layout = new GridLayout(6,6, 10, 10);
panel.setLayout(layout);
for (int i= 0; i < 36; i++){
panel.add(new Button(""));
}
controlPanel.add(panel);
buttomsPanel.add(new Button(""));
frame.add(buttomsPanel);
frame.add(controlPanel);
frame.setSize(900, 700);
基本上我添加到gui的第二个按钮不会显示。另外,我想放另外两个字段,我不知道如何移动它们,或者它们是否应先进入面板然后移动。
答案 0 :(得分:1)
让我们从ambaguity开始...
Button
可以是java.awt.Button
或javafx.scene.control.Button
,在任何一种情况下,它都可能与JPanel
无关。
Panel
是java.awt.Panel
,与Swing不相称。在Swing中不混合使用AWT组件会更容易。
接下来,JFrame
默认情况下使用BorderLayout
,这意味着当您执行类似的操作时...
frame.add(buttomsPanel);
frame.add(controlPanel);
controlPanel
可能是显示的那个(并且考虑到AWT和Swing之间的z排序的奇怪之处,无论你添加它们的顺序如何,都可能希望显示它)。
要解决此问题,您需要在BorderLayout
中指定要添加面板的位置,例如......
frame.add(buttomsPanel);
frame.add(controlPanel, BorderLayout.SOUTH);
并使用JPanel
代替Panel
和JButton
代替Button
...
有关详细信息,请参阅How to Use Borders
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Panel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JPanel controlPanel = new JPanel(new FlowLayout(10));
JPanel chatPanel = new JPanel();
JPanel buttomsPanel = new JPanel();
Panel panel = new Panel();
panel.setBackground(Color.DARK_GRAY);
panel.setSize(700, 700);
GridLayout layout = new GridLayout(6, 6, 10, 10);
panel.setLayout(layout);
for (int i = 0; i < 36; i++) {
panel.add(new JButton(""));
}
controlPanel.add(panel);
buttomsPanel.add(new JButton(""));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(buttomsPanel);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}