我有一个扩展JComponent的自定义组件,它覆盖了方法paintComponent(Graphics g)但是当我尝试将它添加到我的JPanel时它只是不起作用,没有绘制任何东西。 这是我的代码:
public class SimpleComponent extends JComponent{
int x, y, width, height;
public SimpleComponent(int x, int y, int width, int height){
this.x = x;
this.y = y;
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fillRect(x, y, width, height);
}
}
public class TestFrame{
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
panel.add(comp);
frame.setVisible(true);
}
}
答案 0 :(得分:4)
它工作正常 - 组件被添加到JPanel,但它有多大?如果在渲染GUI后检查这一点,您可能会发现组件的大小为0,0。
SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
panel.add(comp);
frame.setVisible(true);
System.out.println(comp.getSize());
考虑让你的JComponent覆盖getPreferredSize并返回一个有意义的Dimension:
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
如果您想使用x和y,您也可以覆盖getLocation()
。
修改强>
您还需要设置宽度和高度字段!
public SimpleComponent(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width; // *** added
this.height = height; // *** added
}
答案 1 :(得分:-2)
哇!绝对不是正确答案!
你承诺的第一个绝对 CARDINAL SIN 是在非EDT线程中完成所有这些!这里没有空间可以解释这个问题......网上只有大约300亿个地方可以了解它。
一旦所有这些代码在EDT(事件调度线程)中的Runnable
中执行,那么:
你不需要覆盖preferredSize
(尽管你可以,但如果你愿意的话)......但你确实需要设置它。
您绝对不应直接设置尺寸(height
和width
或setSize()
)!
你做需要做的就是让你的例子中的java.awt.Container
,panel
“自我解决”......有一种方法{ {1}},但正如API文档中所述:
因此,解决方案是:使此容器布局其组件。大多数程序应该 不直接调用此方法,但应调用validate方法 代替。
Container.doLayout()
顺便说一句,请从我的经验中获益:我花了几个小时的时间撕掉我的头发,试图理解所有这些SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
comp.setPreferredSize( new Dimension( 90, 90 ) );
panel.add(comp);
// the key to unlocking the mystery
panel.validate();
frame.setVisible(true);
等等......我仍然觉得我只是在表面上划过。