我已将java swing应用程序的帧大小设置为: frame.setSize(700,500);
每当我最大化窗口时,我希望UI元素进行调整并获取完整的应用程序大小。 现在,当我最大化时,占据整个窗口的框架保持空白,UI元素保持与以前相同的位置。 我应该更改代码,以便每当我最大化窗口时,UI元素应该占据窗口吗?
答案 0 :(得分:4)
这只是一个示例代码,您可以将其用于您的应用,GridBagConstraint
适用于您需要将weightx
或weighty
属性设置为非零的大小。
import java.awt.*;
import javax.swing.*;
public class app extends JFrame{
public app(String title){
super(title);
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
getContentPane().setLayout(layout);
constraints.anchor = GridBagConstraints.WEST;
JLabel l1 = new JLabel("First Name:");
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 0;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(5,5,5,5);
layout.setConstraints(l1, constraints);
getContentPane().add(l1);
//JTextField t1 = new JTextField(10);
JTextField t1 = new JTextField(); //removed passing column size.
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(5,5,5,5);
layout.setConstraints(t1, constraints);
getContentPane().add(t1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(700,500);
}
public static void main(String[] args){
new app("App").setVisible(true);
}
}