假设我在 JFrame 中有一个 JPanel。当我调用更改该 JPanel 首选大小的方法时,它不会更改。
代码看起来像这样:
public class SomePanel extends JPanel{
public SomePanel(){
setPreferredSize( new Dimension( 390, 40 ) );
setBackground( Color.BLACK );
}
public void expand(){
setPreferredSize( new Dimension( 390, 200 ) );
}
public static void main( String args[] ){
JFrame frame = new JFrame();
frame.setSize( 450, 500 );
frame.setLayout( new FlowLayout() );
SomePanel somePanel = new SomePanel();
frame.add( somePanel );
frame.setVisible( true );
somePanel.expand();
}
}
有什么我必须先做的吗?我尝试过在调用 Expand() 时检查 JPanel 的大小。设置首选尺寸前后 JPanel 的高度保持为 40。
我也尝试过使用 Dimension 变量,但这也不起作用。
Dimension dimension;
public SomePanel(){
dimension = new Dimension( 390, 40 );
...
}
public expand(){
dimension.setSize( 390, 200 );
setPreferredSize( dimension );
}
最佳答案
在 main()
方法中的 somePanel.expand();
之后添加 frame.pack();
。一定会完成的。
关于java - 如何更改 JFrame 中组件的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13549976/