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);
}
}
It works fine -- the component is being added to the JPanel, but how big is it? If you check this after the GUI has been rendered, you'll likely find that your component's size is 0, 0.
SimpleComponent comp = new SimpleComponent(10, 10, 100, 100);
panel.add(comp);
frame.setVisible(true);
System.out.println(comp.getSize());
Consider having your JComponent override getPreferredSize and return a Dimension that makes sense:
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
If you want to use the x and y, you may wish to override getLocation()
as well.
Edit
You also need to set the width and height fields!
public SimpleComponent(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width; // *** added
this.height = height; // *** added
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With