我有一个表单,当它使用 pack
渲染时,文本框有一个很好的默认高度。但是当我调整它的大小时 - 或者在这种情况下,如果我覆盖 getPreferredSize
使其在启动时变大 - 文本框按比例调整大小。
我一直在试图理解布局管理器类...即将出现的相关问题似乎非常接近,但我只是没有关注它们!
在下面的类(class)中,如果我注释掉 getPreferredSize
过载时,系统会将文本框的大小设置为“恰到好处”。添加getPreferredSize
返回,或手动调整大小,文本框比例随表单扩展/收缩。我一定缺少一些简单的东西!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class TestTextBox extends JFrame {
private JTextField jtfRate = new JTextField();//jtfAnnualInterestRate
private JButton jbtComputeLoan = new JButton("Compute Sentence");
// Constructor buids the panel
public TestTextBox() {
// a panel with the fields
JPanel p1 = new JPanel(new GridLayout(5, 2));
p1.add(new JLabel("Annual Interest Rate"));
p1.add(jtfRate);
p1.setBorder(new TitledBorder("This is a border with enough text that I want to see it"));
// a panel with the button
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
p2.add(jbtComputeLoan);
// Put the panels on the frame
add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
}
@Override
public Dimension getPreferredSize() {
// This will help Pack to pack it up better
return new Dimension(600, 300);
}
public static void main(String[] args) {
TestTextBox jailCell = new TestTextBox();
jailCell.pack(); // Arrange controls compactly based on their properties
jailCell.setTitle("Calculate your Sentence");
jailCell.setLocationRelativeTo(null); // sure, center it, whatever
jailCell.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jailCell.setVisible(true);
}
}
显然,这是 GUI 布局工具的情况。但这不是生产代码,这是一个 Java 类,我在其中尽力了解它为何有效 - 这样我就会知道 GUI 工具在做什么。
更新:感谢我得到的答案,我能够了解 GridBag 的基础知识。它似乎与 HTML <table>
密切相关。 s。它花费的时间比应有的时间长得多,主要是因为我一直忘记, c);
应用 GridBagConstraints
到控制!以下是上面相对简单的添加变成的示例:
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
p1.add(new JLabel("Annual Interest Rate"), c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.25;
p1.add(jtfRate, c);
最佳答案
GridLayout 的默认行为是为每个组件提供等量的可用空间。这意味着,当您使组件变大时,它们会变大,当您使组件变小时,它们会变小。
您可以使用 GridBagLayout
来代替,它允许您以网格图案布局组件,但控制它们应占据多少单元格...
看看How to use GridBagLayout了解更多详情...
关于java - 控制 Java Swing 布局中的文本框高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698350/