I have a custom component that extends JComponent, which overrides the method paintComponent(Graphics g) but when I try to add it to my JPanel it just doesn't work, nothing is drawn. Here is my code:
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);
}
}