【发布时间】:2013-10-31 04:17:09
【问题描述】:
我有一个表单,当它使用pack 呈现时,文本框有一个很好的默认高度。但是当我调整它的大小时 - 或者在这种情况下,如果我覆盖 getPreferredSize 以使其在启动时变大 - 文本框会按比例调整大小。
我一直在兜圈子,试图理解布局管理器类......即将出现的相关问题似乎非常接近,但我只是没有关注它们!
在下面的课程中,如果我注释掉 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 应用于控件!下面是上面相对简单的 add 变成的示例:
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);
【问题讨论】:
-
我能知道你用的是什么ide吗?
-
@NiteshVerma 我正在使用 jGRASP,至少目前是这样。然而,它迷人的智能感知缺失开始让我头疼。
-
您可以尝试 Netbeans,因为我个人将它用于桌面应用程序开发,因为它非常强大且有效。
标签: java swing layout jpanel layout-manager