【发布时间】:2014-05-21 14:45:15
【问题描述】:
在带有 GridBagLayout 的 JPanel 中,我创建了与 JscrollPane 组件绑定的 JTextPane 组件列表。不幸的是,组件的大小似乎是固定的:当我减小 JFrame 大小时,我想强制组件动态地使其大小适合 JFrame。 例如,当主窗口大小减小到 20 像素时,我希望组件也将其大小更改为 20 像素。
这是我的代码:
import java.awt.*;
import javax.swing.*;
public class ScrollbarTest {
private JFrame frame;
private JPanel panel;
private JScrollPane [] scrollpane = new JScrollPane[4];
private JTextArea [] textPane = new JTextArea[4];
private JScrollPane scrollbar;
ScrollbarTest() {
//initialize jtextarea
for(int i=0;i<textPane.length;i++) {
textPane[i]=new JTextArea();
textPane[i].setText("xxxx xxxx xxxx xxxx xxxx xxxx xxxx | ");
scrollpane[i] = new JScrollPane(textPane[i]);
scrollpane[i].setMinimumSize(new Dimension(100,100));
}
panel = new JPanel();
frame = new JFrame();
createList(panel);
scrollbar = new JScrollPane(panel);
frame.add(scrollbar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(new Dimension(400,400));
} //constructor
//method to easily add components to GridBags
static void addComponent(JPanel panel,
GridBagLayout gbl,
Component c,
int x, int y,
int width, int height,
double weightx, double weighty) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = width; gbc.gridheight = height;
gbc.weightx = weightx; gbc.weighty = weighty;
gbl.setConstraints( c, gbc );
panel.add( c );
}//addComponent
public void createList(JPanel panel) {
//setting layout: "GridBagLayout"
GridBagLayout gbl = new GridBagLayout();
panel.setLayout(gbl);
//put created components to the gridbags of gridbaglayout
// x y w h wx wy
addComponent( panel, gbl, scrollpane[0] , 0, 1, 1, 1, 1 ,1 );
addComponent( panel, gbl, scrollpane[1] , 0, 2, 1, 1, 1 ,1 );
addComponent( panel, gbl, scrollpane[2] , 1, 1, 1, 1, 1 ,1 );
addComponent( panel, gbl, scrollpane[3] , 1, 2, 1, 1, 1 ,1 );
} //createList
public static void main (String[] args) {
new ScrollbarTest();
} //main
} //end of class
如何动态调整组件的大小?
非常感谢!
【问题讨论】:
标签: java resize jscrollpane jtextpane