大約一個月前,我有一個 Java 作業,是關于構建一個 GUI。我使用 GroupLayout 來管理組件的位置。我遇到了一個問題,如果我將很長的文本字串放入 JTextField 并調整外部視窗的大小,文本欄位會突然“爆裂”。
我使用 GridBagLayout 解決了這個問題,但我想回到原來的問題,希望能更好地理解 GroupLayout。
這是一個演示此問題的 SSCCE。(我盡量減少它,如果我的例子太長,我很抱歉。)
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
JTextField text1;
JTextField text2;
JPanel myPanel;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(() -> new Main());
}
public Main() {
super("Sussy Imposter");
createComponents();
setLayout();
configureSettings();
}
public void createComponents() {
text1 = new JTextField(20);
text2 = new JTextField(20);
text1.setMaximumSize(text1.getPreferredSize());
text2.setMaximumSize(text2.getPreferredSize());
myPanel = new JPanel();
myPanel.setBackground(Color.CYAN);
myPanel.setPreferredSize(new Dimension(100, 100));
}
public void setLayout() {
Container c = getContentPane();
GroupLayout groupLayout = new GroupLayout(c);
c.setLayout(groupLayout);
groupLayout.setAutoCreateGaps(true);
groupLayout.setAutoCreateContainerGaps(true);
groupLayout.setHorizontalGroup(
groupLayout.createSequentialGroup()
.addComponent(myPanel)
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(text1)
.addComponent(text2))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup()
.addComponent(myPanel)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(text1)
.addComponent(text2))
);
}
public void configureSettings() {
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}

當我將此文本復制粘貼Let me send you to space ??Space travel ASMR Roleplay ??(Eng)(Kor) | Roleplay, Storytime, Whitenoise到其中一個文本欄位中并調整外部視窗的大小時,文本欄位會“爆裂”。

我已將文本欄位的最大大小設定為它們的首選大小createComponents(),所以我不明白為什么當我調整視窗大小時文本欄位的大小超過其最大大小。
誰能解釋為什么我會出現這種奇怪的行為?
編輯:我已經重寫了該paint()方法以查看文本欄位大小的寬度如何變化。
public void paint(Graphics g) {
super.paint(g);
System.out.printf("min: %d\n", text1.getMinimumSize().width);
System.out.printf("pre: %d\n", text1.getPreferredSize().width);
System.out.printf("max: %d\n", text1.getMaximumSize().width);
}
調整大小前的輸出
min: 5
pre: 224
max: 224
調整大小后的輸出
min: 569
pre: 224
max: 224
正如@matt 在評論中指出的那樣,這似乎是因為 minimumSize 變得非常大。更值得注意的是,minimumSize 增長大于preferredSize 和maximumSize,這是非常出乎意料的。
uj5u.com熱心網友回復:
編輯:最小尺寸的行為,在調整大小后增長,并變得大于最大尺寸似乎是一個錯誤。
顯式設定最小大小是一種解決方法:
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(text1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(text2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
這會將組件的最小和最大尺寸設定為默認尺寸,如檔案中所述:
使組件固定大小(抑制調整大小): group.addComponent(component, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
您可以通過設定最小和最大尺寸來實作相同的行為:
text1.setMinimumSize(text1.getPreferredSize());
text1.setMaximumSize(text1.getPreferredSize());
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/408902.html
標籤:
下一篇:JavaSwing中的聊天框區域
