所以我在 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 的主要优点是调整大小。当您调整大小时,您的组件也会相应地调整大小。
希望这对您有帮助。 :-)
关于java防止组件在框架调整大小时调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45273040/