简体   繁体   English

如何使元素根据JAVA swing中窗口的大小自动调整其大小?

[英]How do I make the elements automatically adapt their sizes according to the size of window in JAVA swing?

The IDE I use is Intellij. 我使用的IDE是Intellij。 Here I created a small program of converting currency. 在这里,我创建了一个转换货币的小程序。 I used BorderLayout as the root panel and flowLayout for the bottom buttons. 我使用BorderLayout作为根面板,并使用flowLayout作为底部按钮。 For west and east panel I used GridLayout(Intellij). 对于东西方面板,我使用了GridLayout(Intellij)。 When I run the program, it can display normally like this: 当我运行该程序时,它可以正常显示如下:

在此处输入图片说明

After changing its size, the gap between elements begin to expand like this: 更改大小后,元素之间的间隙开始扩大,如下所示: 在此处输入图片说明

How do I make them adjust the distance automatically? 如何让他们自动调整距离?

Here are my codes: 这是我的代码:

  import javax.swing.*;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;

  /**
   * Created by Bob on 2017/5/11.
   */



 public class layout {

private JPanel converterRootPanel;
private JPanel westPanel;
private JLabel selectNationPanel;
private JLabel currencyToConvett;
private JLabel currencyConverted;
private JComboBox currencyType;
private JTextField input;
private JTextField output;
private JPanel eastPanel;
private JPanel southPanel;
private JButton convertButton;
private JButton clearButton;
private JLabel convertToLabel;
private JComboBox convertType;
private JPanel northPanel;
public int selection1;
public int selection2;
public Double toConvert;
public double[][] rate1={{0,0.1335,0.1449,16.5172,163.4922},{7.4927,0,1.0857,123.7900,
        1225.0380},{6.9029,0.9382,0,114.01,1129.19},{0.06053,0.00808,0.008771,0,9.9043},{0.006112,
        0.0008158,0.0008856,0.101,0}};

public layout() {
    currencyType.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            selection1 = currencyType.getSelectedIndex();
        }
    });
    convertType.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            selection2 = convertType.getSelectedIndex();
        }
    });

    convertButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(selection1==selection2){
                JOptionPane.showConfirmDialog(null, "You have to choose different currency types!", "Error Alert", JOptionPane.CANCEL_OPTION);
            }
            output.setText("");
            toConvert = Double.parseDouble(input.getText().toString());
            Double convertResult = toConvert*rate1[selection1][selection2];
            output.setText(convertResult.toString());
        }
    });
    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            output.setText("");
            input.setText("");
            convertType.setSelectedIndex(0);
            currencyType.setSelectedIndex(0);
        }
    });
}

public static void main(String[] args) {
    JFrame frame = new JFrame("layout");
    frame.setContentPane(new layout().converterRootPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    //layout lay = new layout();
}

private void createUIComponents() {
    // TODO: place custom component creation code here
}

} }

What you want to do is done through a layout manager. 您想要做的是通过布局管理器完成的。 There are several of these for Java that are part of the standard library and there are also other custom ones such as MigLayout. 其中有一些Java语言是标准库的一部分,还有其他自定义语言,例如MigLayout。

The Java tutorials have a whole section on layout managers here Java教程在这里有一整节关于布局管理器的内容


A basic example of the GridBagLayout would be the following. GridBagLayout一个基本示例如下。

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Basic {
    JFrame frame;
    JPanel panel;
    JLabel label;
    JButton button;

    public void createAndRun() {
        frame = new JFrame("Basic Example");

        setUp();
        frame.getContentPane().add(panel);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void setUp() {
        panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        label = new JLabel("I am a JLabel");
        c.gridx = 0;
        c.gridy = 0;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 0.5;
        c.weighty = 0;
        panel.add(label, c);

        button = new JButton("I am a JButton");
        c.gridx = 0;
        c.gridy = 1;
        c.weighty = 0.5;
        panel.add(button, c);
    }

    public static void main(String[] args) {
        Basic b = new Basic();
        b.createAndRun();
    }
}

However, as the tutorials put it. 但是,正如教程所述。

"GridBagLayout is one of the most flexible — and complex — layout managers the Java platform provides." “ GridBagLayout是Java平台提供的最灵活(也是最复杂)的布局管理器之一。”

So if you are having problems with GridBagLayout it may be worth looking at other layout managers beforehand. 因此,如果您在使用GridBagLayout时遇到问题,可能值得事先咨询其他布局管理器。


Finally, I would like to suggest some ways that you might look at improving your code. 最后,我想提出一些您可以用来改进代码的方法。

The part that caught my eye the most was this line. 最吸引我眼球的部分是这条线。

frame.setContentPane(new layout().converterRootPanel);

I would recommend not creating the JFrame and initialising you Layout class in the main method. 我建议不要在main方法中创建JFrame并初始化Layout类。 Instead, it would be worth initialising the class first and then calling a method to create the frame. 相反,值得首先初始化类,然后调用方法创建框架。

Layout l = new Layout();
l.createFrame();

This is shown in the example code above. 如上面的示例代码所示。

A GridBagLayout uses the weightx and weighty properties of GridBagConstraints to determine how extra space is distributed. GridBagLayout使用GridBagConstraints的weightxweighty属性来确定如何分配额外的空间。 GridBagLayout uses the largest weightx of all cells in a column to determine the column's actual horizontal weight for all cells in that column, and similarly, the largest weighty of all cells in a row determines that row's vertical weight. GridBagLayout的使用最大weightx所有单元的一列中,以确定用于该列中的所有单元格列的实际水平权重,并且类似地,最大weighty行中的所有单元的判定行的垂直权重。 If all columns have a zero weightx, they are all centered horizontally. 如果所有列的权重均为零,则它们都水平居中。 If all rows have a zero weighty, they are all centered vertically. 如果所有行的权重均为零,则它们都垂直居中。

Usually a good design is to have the input fields stretch horizontally, while the labels remain the same size at all times. 通常,一个好的设计是使输入字段水平延伸,而标签始终保持相同大小。 You probably want the rows to have same vertical spacing at all times, and have all extra space appear above or below the entire set of rows. 您可能希望行始终具有相同的垂直间距,并且所有多余的空间都出现在整个行集的上方或下方。

To make all cells of a particular column stretch, you only need to set the weightx of one cell in that column: 要拉伸特定列的所有单元格,只需设置该列中一个单元格的weightx

JPanel buttonPanel = new JPanel();
buttonPanel.add(convertButton);
buttonPanel.add(clearButton);

converterRootPanel = new JPanel(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_END;

// First row

converterRootPanel.add(selectNationPanel, gbc);

gbc.weightx = 1;

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
converterRootPanel.add(currencyType, gbc);

gbc.weightx = 0;
gbc.insets.top = 3;

// Second row

gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
converterRootPanel.add(convertToLabel, gbc);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
converterRootPanel.add(convertType, gbc);

// Third row

gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
converterRootPanel.add(currencyToConvett, gbc);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
converterRootPanel.add(input, gbc);

// Fourth row

gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
converterRootPanel.add(currencyConverted, gbc);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
converterRootPanel.add(output, gbc);

// Button row

gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.CENTER;
converterRootPanel.add(buttonPanel, gbc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM