Java 可防止组件在调整帧大小时调整大小



所以我有一堆组件,这些组件被布置在JPanel中,以制作一个允许用户输入字符的GUI。但是,当调整JFrame的大小时,组件会变得疯狂并缩小一吨。有没有办法解决这个问题,或者我应该禁用调整 JFrame 的大小。我基本上希望它保持所有组件的大小相同,并在窗口太小时切掉组件。我见过有人说GridBagLayout可以解决这个问题,但我仍然不知道该怎么做。

法典:

public class CharacterWrapper extends JPanel {
private int currentID = 0;
private JFrame parent;
private ArrayList<CharacterInput> inputSlots = new ArrayList<CharacterInput>();
/**
* 
*/
public CharacterWrapper(JFrame parent) {
this.parent = parent;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(e -> {
deleteInput();
parent.pack();
});
JButton addButton = new JButton("Add");
addButton.addActionListener(e -> {
addInput();
parent.pack();
});
add(addButton);
add(deleteButton);
addInput();
addInput();
addInput();
}
public void addInput() {
inputSlots.add(new CharacterInput(currentID++, this));
add(inputSlots.get(inputSlots.size() - 1));
revalidate();
}
public void deleteInput() {
if (inputSlots.size() > 3) {
Component c = inputSlots.remove(inputSlots.size() - 1);
remove(c);
revalidate();
currentID--;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new CharacterWrapper(frame));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}

还有更多代码:

public class CharacterInput extends JComponent{
private int id;
private CharacterWrapper parent;
/**
* 
*/
public CharacterInput(int id, CharacterWrapper parent) {
this.parent = parent;
this.id = id;
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
JTextField textField = new JTextField();
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) { 
if (textField.getText().length() >= 1) 
e.consume(); 
} 
});
textField.setPreferredSize(new Dimension(35, 35));
JLabel label = new JLabel(id + "", SwingConstants.CENTER);
add(textField);
add(label);
this.setBackground(Color.RED);
}
}

我建议仅在添加动态组件(例如在用户按下按钮时添加 JTextField(时才使用 GridLayout 或 GridBagLayout。

我建议你使用BorderLayout。它很简单,您可以轻松玩。

例如:你有 8 个组件要放置在 JFrame 上,但 BorderLayout 只有 5 个边。因此,使用BorderLayout添加一个父面板,将另一个JPanel(带有BorderLayout(添加到父面板的北部。这样,您可以总共添加 9 个组件。

使用 BorderLayout 的主要优点是调整大小。调整大小时,组件也会相应地调整大小。

希望这对你有帮助。

也许这会有所帮助。以这种方式使用GridBagConstraints

public void addInput() {
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = i;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.CENTER;
inputSlots.add(new CharacterInput(currentID++, this));
add(inputSlots.get(inputSlots.size() - 1), gbc);
repaint();
revalidate();

使用gbc.weightx = 1将帮助您消除组件的收缩。

最新更新