我对Java很陌生,我正在玩一个简单的GUI示例:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class DrawTest {
class DrawingPanel extends JPanel {
private Rectangle2D shape;
public DrawingPanel(Rectangle2D shape) {
this.shape = shape;
}
public void paintComponent(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
super.paintComponent(g2D);
g2D.setColor(new Color(31, 21, 1));
g2D.fill(shape);
}
}
public void draw() {
JFrame frame = new JFrame();
Rectangle2D shape = new Rectangle2D.Float();
final DrawingPanel drawing = new DrawingPanel(shape);
shape.setRect(0, 0, 400, 400);
frame.getContentPane().add(BorderLayout.NORTH, new JButton("TestN"));
frame.getContentPane().add(BorderLayout.SOUTH, new JButton("TestS"));
frame.getContentPane().add(BorderLayout.EAST, new JButton("TestE"));
frame.getContentPane().add(BorderLayout.WEST, new JButton("TestW"));
frame.getContentPane().add(BorderLayout.CENTER, drawing);
frame.pack();
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
public class DrawMain {
public static void main(String[] args) {
DrawTest test = new DrawTest();
test.draw();
}
}正如预期的那样,该代码生成一个以矩形为中心的框架,并在其周围设置按钮。但是,如果我像这样更改代码:
frame.getContentPane().add(BorderLayout.NORTH, drawing);
frame.getContentPane().add(BorderLayout.SOUTH, new JButton("TestS"));
frame.getContentPane().add(BorderLayout.EAST, new JButton("TestE"));
frame.getContentPane().add(BorderLayout.WEST, new JButton("TestW"));
frame.getContentPane().add(BorderLayout.CENTER, new JButton("TestC"));"TestC“按钮在中间有一个很大的区域,而矩形没有足够的空间。如果删除其他按钮(TestS、TestE、TestW),这甚至是正确的:我在顶部得到一个巨大的TestC按钮和一个很小的矩形(甚至不是缩放的矩形)。
为什么矩形在顶部(北)画的时候没有足够的空间,而在中心画的时候却没有足够的空间?
发布于 2020-04-30 18:02:58
DrawingPanel应该@Override getPreferredSize()来返回一个适当的大小。
然后,布局管理器将以该首选大小作为提示。一些布局管理器会根据布局和约束的逻辑来扩展组件的高度或宽度。例如,BorderLayout将把PAGE_START / PAGE_END中的组件拉伸到内容窗格的宽度,而LINE_START / LINE_END将拉伸到其中任何一个最高的组件或CENTER的高度。GridBagLayout OTOH将完全隐藏/删除没有足够空间以首选大小显示它的组件,这就是“pack”出现的地方。
因此,将frame.setSize(500,500); (这并不比猜测更好)改为frame.pack();,这将使帧达到它所需的最小大小,以便显示它包含的组件。
https://stackoverflow.com/questions/61460081
复制相似问题