Java- - 调整打包的JFRame

时间:2016-06-19 13:21:36

标签: java jframe

当我使用frame.pack();时,我看到一个非常小的窗口:

enter image description here

包装后调整大小使框架难看。

我怎样才能获得大而且整齐的画面?

代码:

public class Main {

//first tab
static JTextArea nameArea = new JTextArea("Nickname:");
static JTextArea ageArea = new JTextArea("Age:");
static JTextArea heightArea = new JTextArea("Height:");
static JTextArea weightArea = new JTextArea("Weight:");

static JTextField nameField = new JTextField();
static JTextField ageField = new JTextField();
static JTextField heightField = new JTextField();
static JTextField weightField = new JTextField();

public static void main(String[] args) {
    JFrame frame = new JFrame("Character Builder");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(512, 384));
    frame.setVisible(true);

    JTabbedPane pane = new JTabbedPane();
    frame.add(pane);

    JPanel panel1 = new JPanel();
    GridLayout layout = new GridLayout(4, 2);
    layout.minimumLayoutSize(panel1);
    panel1.setLayout(layout);
    pane.addTab("Profile", panel1);

    JButton button = new JButton("test");
    panel1.add(nameArea);
    panel1.add(nameField);
    panel1.add(ageArea);
    panel1.add(ageField);
    panel1.add(heightArea);
    panel1.add(heightField);
    panel1.add(weightArea);
    panel1.add(weightField);

    frame.pack();
}

}

1 个答案:

答案 0 :(得分:0)

更改组件的首选大小。

http://docs.oracle.com/javase/8/docs/api/java/awt/Window.html#pack--

编辑:好的,pack()仅适用于标签窗格中的“out farest”组件。另一方面,GridLayout定位于最小宽度和高度,在这种情况下显然是Nickname:的宽度和文本字段的高度,您也可以更改它们。 ( EDIT2:在尝试之后我发现仍然使用了preferredSized,无论出于何种原因)参见:

http://docs.oracle.com/javase/8/docs/api/java/awt/GridLayout.html#minimumLayoutSize-java.awt.Container-

如果您愿意,还可以更改组件之间的间隙。

EDIT2:这就是我能为您提供的全部内容。

    JPanel panel1 = new JPanel();
    GridLayout layout = new GridLayout(4, 2);
//    layout.minimumLayoutSize(panel1);
    layout.setHgap(1);
    layout.setVgap(10);
    panel1.setLayout(layout);
    pane.addTab("Profile", panel1);

    Dimension dmtfs = nameField.getPreferredSize(); // default preferred text field size
    nameField.setPreferredSize(new Dimension(dmtfs.width, dmtfs.height-10)); // too small, but will be caught by height of text area 
    ageField.setPreferredSize(new Dimension(dmtfs.width, dmtfs.height-10));
    heightField.setPreferredSize(new Dimension(dmtfs.width, dmtfs.height-10));
    weightField.setPreferredSize(new Dimension(dmtfs.width, dmtfs.height-10));
    Dimension dmtas = nameArea.getPreferredSize(); // default preferred text area size
    nameArea.setPreferredSize(new Dimension(dmtas.width+10, dmtas.height));
    // changing one is enough, because GridLayout goes for the biggest

网格布局将尝试使每个组件具有相同的大小,而在JTextField的情况下,这意味着填充所有可用空间。