不知道我是否犯了新手错误,但在我的JFrame中为JPanel创建GridLayout时更改row参数似乎导致另一个JPanel完全消失:
这是代码的精简版本:
我不知道我做错了什么:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GridBug extends JFrame{
static class ImagePanel extends JPanel{
@Override
public Dimension getPreferredSize(){
return new Dimension(200,200);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println("Painting image panel...");
g.setColor(Color.CYAN);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public GridBug() {
setLayout(new BorderLayout());
/*PROBLEM CODE HERE*/
//add center image panel - does not appear depending on GridLayout settings in other panels
ImagePanel centerPanel = new ImagePanel();
add(centerPanel , BorderLayout.CENTER);
//add bottom panel
JPanel bottomPanel = new JPanel();
add(bottomPanel, BorderLayout.PAGE_END);
bottomPanel.setLayout(new GridLayout(6,0)); //doesn't work
// bottomPanel.setLayout(new GridLayout(5,0)); //works
JPanel subPanel = new JPanel();
//if I pass more than 4 or so rows as param to gridlayout,
//then imagePanel is not displayed
subPanel.setLayout(new GridLayout(4,0)); //doesn't work
// subPanel.setLayout(new GridLayout(3, 0)); //works
//if I don't add this label - works
JLabel label = new JLabel("A Label:");
subPanel.add(label);
bottomPanel.add(subPanel); //if I don't add the subPanel it works fine
/*END OF PROBLEM CODE?*/
//set window params
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setLocationRelativeTo(null);
setVisible(true);
}
public static final void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GridBug();
}
});
}
}
答案 0 :(得分:3)
不确定您想要的确切结果,所以我甚至都没有尝试过。但是您遇到的问题是其中一个原因,您想要pack()
您的框架,而不是setSize()
。您正在限制组件的首选大小。 pack()
尊重所有组件的首选大小,应该使用,而不是setSize()
bottomPanel.setLayout(new GridLayout(6,0)); //doesn't work..
// with pack(), now it does.
pack();
//setSize(400,400); // if you increase the size it'll work also, but just pack()
您现在只需要处理组件的布局以获得所需的外观:)
您问题的更详细解释。
这是我设置背景时当前代码的显示方式。注意:您已经看到setSize()
会影响您的顶部面板的首选尺寸(200,200)。
subPanel
,有4行。使用GridLayout,所有行都至少是最大组件的大小。在这种情况下,它是标签。您可以看到蓝色区域是标签高度的4倍(应该是)bottomPanel
。这有5行。最大的组件是subPanel
,因此bottomPanel
的总大小是subPanel
x 5的大小,您也可以看到。添加另一行后,顶部面板将被推出。