gpt4 book ai didi

java - 使用 GridBagLayout 时如何将 TextArea 从 "snapping"停止为不同的大小

转载 作者:行者123 更新时间:2023-12-01 12:06:41 24 4
gpt4 key购买 nike

我正在尝试了解 GridBagLayout,并且我已经让我的 TextArea 组件按照我想要的方式运行,除非窗口垂直调整大小时除外。

当窗口大小调整为更短时,底部 TextArea 会捕捉到更大的尺寸,而不是保持当前尺寸,并在空间不足时根据权重缩小。

我觉得这很简单,比如改变填充什么的,但我不明白......

代码:

public class Window {

Frame frame;
Panel panel;
TextArea top;
TextArea bottom;
GridBagConstraints topC, bottomC;

Window(){
createWindow();
}


public static void main(String[] args){
new Window();
}


private void createWindow(){
//create panel for text areas
panel = new Panel(new GridBagLayout());

//create top text area
top = new TextArea();
top.setPreferredSize(new Dimension(500,500));

//create bottom text area
bottom = new TextArea();
bottom.setPreferredSize(new Dimension(500,75));

//set constraints for top text area
topC = new GridBagConstraints();
topC.anchor = GridBagConstraints.NORTH;
topC.fill = GridBagConstraints.BOTH;
topC.gridheight = GridBagConstraints.RELATIVE;
topC.gridwidth = GridBagConstraints.REMAINDER;
topC.gridx = 0;
topC.gridy = 0;
topC.insets = new Insets(2,2,2,2);
topC.weightx = 1.0;
topC.weighty = 1.0;

//set constraints for bottom text area
bottomC = new GridBagConstraints();
bottomC.anchor = GridBagConstraints.SOUTH;
bottomC.fill = GridBagConstraints.BOTH;
bottomC.gridheight = GridBagConstraints.REMAINDER;
bottomC.gridwidth = GridBagConstraints.REMAINDER;
bottomC.gridx = 0;
bottomC.gridy = 1;
bottomC.insets = new Insets(2,2,2,2);
bottomC.weightx = 1.0;
bottomC.weighty = 0.5;

//add text areas to the panel
panel.add(top, topC);
panel.add(bottom, bottomC);

//create frame
frame = new JFrame();
frame.setTitle("Client Console");
frame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
frame.dispose();
}
});
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

}

}

最佳答案

将文本区域放在 scroll pane 中。

您可能还想看看Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

您真的需要使用 AWT 吗?它有点过时了(比如已经过时 15 年了)。如果您可以考虑使用 Swing 或 JavaFX...

关于java - 使用 GridBagLayout 时如何将 TextArea 从 "snapping"停止为不同的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com