我有代码
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.FlowLayout;
class GUI extends JFrame {
JPanel mainPanel;
public GUI(String header) {
super(header);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(new FlowLayout(FlowLayout.CENTER));
init();
add(mainPanel);
pack();
}
public void init() {
mainPanel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
g.fillOval(0, 0, 50, 50);
}
};
}
}
在我的主要方法中,我有
GUI progam = new GUI("Title");
progam.setLocationRelativeTo(null);
progam.setVisible(true);
如果我运行该程序,我会得到输出:
如果我取消注释 setLayout
,我会得到输出:
两个问题:
- 为什么在第一种情况下
pack()
没有按预期工作?难道我不应该看到整个圆圈而不是看到一半吗? - 为什么第二个输出中椭圆形变成了三角形?
最佳答案
Why isn't pack() working as expected in the first case? Shouldn't I see the full circle instead of seeing half of it?
确实,您的 mainPanel
没有为布局管理器提供任何大小调整提示,因此它使用组件的默认大小调整提示 (0x0)
添加
@Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
在进行任何自定义绘画之前,将 mainPanel
和 super.paintComponent(g)
发送给您的 paintComponent
方法
Why did the oval turn into a triangle in the second output?
这就是 BorderLayout
和 FlowLayout
之间的区别
关于java - `pack()` 和 `setLayout()` 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31184014/