我有2个Java类,Game
和BaseComponent
。
我想在JFrame
中绘制多个组件,但这不起作用,因为它只显示最后添加的组件。
我认为解决方案是添加一个JPanel
,但这仍然不适合我,因为没有对象被绘制,甚至没有。
public class Game
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jpanel = new JPanel();
JComponent component = new BaseComponent(0,0);
JComponent component2 = new BaseComponent(1,1);
jpanel.add(component);
jpanel.add(component2);
frame.add(jpanel);
frame.setVisible(true);
}
}
public class BaseComponent extends JComponent
{
private int x, y;
BaseComponent(int i, int y) {
this.x = i;
this.y = y;
}
@Override
public Dimension getPreferredSize() {
return new Dimension((x * 50) + 50, (y * 50) + 50);
}
@Override
protected void paintComponent(Graphics g)
{
drawBaseComponent(g, x, y);
}
void drawBaseComponent(Graphics g, int x, int y)
{
g.setColor(Color.GREEN);
g.fillRect(x*50, y*50, 50, 50);
}
}
正如您所看到的,此代码会向面板添加一个组件,该组件将添加到JFrame
,但它完全为空;
编辑: 当使用首选尺寸时,应用程序绘制两个绿色框但位置不正确,我预计它们代替两个红色框。
答案 0 :(得分:1)
JPanel
默认使用FlowLayout
。这会尝试将任何组件的大小调整为preferredSize
,默认情况下为0x0
,这就是为什么您的组件出现了"空。
您需要通过getPreferredSize
提供大小调整提示,以便布局管理API确定布局组件的最佳方式,例如
public class BaseComponent extends JComponent
{
private int x, y;
BaseComponent(int i, int i0) {
this.x = i;
this.y = i0;
}
@Override
public Dimension getPreferredSize() {
return new Dimension((x * 50) + 50, (y * 50) + 50);
}
@Override
protected void paintComponent(Graphics g)
{
drawBaseComponent(g, x, y);
}
void drawBaseComponent(Graphics g, int xLeft, int yTop)
{
g.setColor(Color.GREEN);
g.fillRect(x*50, y*50, 50, 50);
}
}