我有一个扩展 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);
}
}