假设JFrame
只包含1 JPanel
。此JPanel
分为2 JPanel
个,相应地占据0.75
高度的0.25
和JFrame
。我希望所有这些都可以与窗口大小一起调整。
我不知道如何在Java中这样做。
我是Java的新手。我已经阅读了一些关于布局的内容,但我只能看到如何在构造函数中设置首选大小(当达到此数字时停止调整大小)或通过设置边框获得一些固定大小。
答案 0 :(得分:4)
JFrame
的 BorderLayout
,添加JPanel
GridBagLayout
。将其他两个面板添加到此。
有关详细信息,请参阅Laying Out Components Within a Container和How to Use GridBagLayout
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 0.75;
JPanel top = new JPanel(new GridBagLayout());
top.add(new JLabel("Top"));
top.setBackground(Color.RED);
add(top, gbc);
gbc.gridy++;
gbc.weighty = 0.25;
JPanel bottom = new JPanel(new GridBagLayout());
bottom.add(new JLabel("Bottom"));
bottom.setBackground(Color.BLUE);
add(bottom, gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}