使用LayoutManagers使TextField正常大小

时间:2014-11-23 18:11:50

标签: java swing awt layout-manager

My GUI Frame

在上面的图片中,这就是我的GUI的样子,我在修复文本字段时遇到问题,因为它占用了我框架中最大百分比的空间,我想纠正我的错误。 我知道布局管理器是一个痛苦的屁股,但有谁知道如何使文本字段更小,以便我的框架看起来更好。

我正在使用jpanel来容纳我的大多数组件

这是我的代码的必要部分

panel1 = new JPanel();
    panel1.setLayout(new GridLayout());
    frame.getContentPane().add(panel1, BorderLayout.NORTH);

        label2 = new JLabel("Score: " + score);
        label2.setFont(new Font("SimSun", Font.BOLD, 22));
        label2.setLocation(0,0);
        label2.setSize(117,37);
        panel1.add(label2);

        label3 = new JLabel("Lives: " + lives);
        label3.setFont(new Font("SimSun", Font.BOLD, 22));
        label3.setLocation(0,70);
        label3.setSize(105,49);
        panel1.add(label3);

    panel2 = new JPanel();
    panel2.setLayout(new BorderLayout());
    frame.getContentPane().add(panel2, BorderLayout.CENTER);

        label1 = new JLabel(a +" + " +b);
        label1.setFont(new Font("SimSun", Font.BOLD, 22));
        label1.setHorizontalAlignment(SwingConstants.CENTER);
        Border paddingBorder = BorderFactory.createEmptyBorder(10,10,10,10);
        label1.setBorder(BorderFactory.createCompoundBorder(null,paddingBorder));
        label1.setLocation(249,105);
        label1.setSize(183,60);
        panel2.add(label1, BorderLayout.NORTH);

        box1 = new JTextField();
        box1.setPreferredSize(new Dimension(50, 50));
        box1.setLocation(249,176);
        box1.setSize(96,25);
        panel2.add(box1, BorderLayout.CENTER);

    panel3 = new JPanel();
    panel3.setLayout(new GridLayout());
    frame.getContentPane().add(panel3, BorderLayout.SOUTH);

        button1 = new JButton("Answer");
        panel3.add(button1);
        button1.addActionListener(this);
        button1.setLocation(187,236);
        button1.setSize(105,50);

        button2 = new JButton("Reset");
        panel3.add(button2);
        button2.addActionListener(this);
        button2.setVisible(false);
        button2.setLocation(302,236);
        button2.setSize(105,50);

1 个答案:

答案 0 :(得分:3)

原因是您要将JTextField添加到BorderLayout.CENTER,这会将其拉伸以填充此特定布局管理器可用的所有空间。虽然我不确定您希望GUI看起来如何,但JTextField上的简单FlowLayout(默认布局)或BoxLayout加上setAlignmentX(Component.CENTER_ALIGNMENT);可能会解决您的问题。< / p>

您可以在此处找到有关布局的更多信息:https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

此外,请注意,您不应该使用setLocation()之类的内容,因为布局管理器的目的是允许它选择如何在屏幕上布置组件,以及布局经理可能会忽略此问题以及setSize等方法。