该应用程序不会调整其组件的大小
我有这个应用程序,但是,当我调整窗口大小时,其中的元素 JTextArea
不会随窗口调整大小。为什么?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExampleGUI {
private JTextArea text_area;
private JScrollPane scroll_bar;
private JFrame frame;
private JPanel panel;
public ExampleGUI(){
frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text_area = new JTextArea();
scroll_bar = new JScrollPane(text_area);
panel = new JPanel();
panel.add(scroll_bar);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){public void run(){new ExampleGUI();}});
}
}
I have this app, but, when I resize the window, the element JTextArea
inside, it doesn't resize with the window. Why?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExampleGUI {
private JTextArea text_area;
private JScrollPane scroll_bar;
private JFrame frame;
private JPanel panel;
public ExampleGUI(){
frame = new JFrame("Example GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text_area = new JTextArea();
scroll_bar = new JScrollPane(text_area);
panel = new JPanel();
panel.add(scroll_bar);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){public void run(){new ExampleGUI();}});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将 GridBagConstraint x 和 y 权重(weightx 和weighty——GridBagConstraint 构造函数中的第 5 个和第 6 个参数)设置为除 0.0 之外的正值。如果您要使用 GridBagLayout,您应该阅读有关 GridBagLayout 的教程,因为它相当复杂。有些在嵌套更简单的布局或使用第三方布局(例如 MigLayout)方面取得了巨大成功。
You need to set your GridBagConstraint x and y weights (weightx and weighty -- the 5th and 6th parameters in the GridBagConstraint constructor) to a positive value other than 0.0. You should read tutorials on GridBagLayout if you're going to use it as it is fairly complex. Some have had great success nesting simpler layouts or using 3rd party layouts such as MigLayout.
您的框架布局是 FlowLayout。这不会调整子项的大小。来自文档:
您最好使用 BorderLayout 并将窗格放在中心。
将其替换
为:
另外,正如 Hovercraft 指出的那样,如果您需要在调整窗格大小时调整各个组件的大小,那么您需要在 GridBagConstraints 中具有非零权重。
Your frame layout is a FlowLayout. This does not resize children. From the docs:
You will be better off using a BorderLayout and putting the pane in the CENTER.
Replace this:
with this:
Also, as Hovercraft points out, if you need the individual components to resize when the pane resizes, then you need to have non-zero weights in the GridBagConstraints.
这考虑到了 Hovercraft Full Of Eels & 的建议。特德·霍普 (Ted Hopp) 进行了一些其他调整。
This takes into account the advice of Hovercraft Full Of Eels & Ted Hopp with a few other tweaks.