JComponent not Drawing to JPanel
Asked Answered
B

1

7

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);
}
}
Brigette answered 6/10, 2012 at 11:13 Comment(0)
L
4

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
}
Logwood answered 6/10, 2012 at 11:17 Comment(6)
That is really strange, ive replicated this problem on windows and mac and its always exactly the sameBrigette
Ah, the width and height is set to zeroBrigette
After remembering to set the width and height fields it still didn't work but when I had overridden the method getPreferredSize() it worked.Brigette
@lilroo: yes you need to do both.Logwood
Also, please call super.paintComponentTurkic
See my answer for why this is absolutely the wrong answer!Guttural

© 2022 - 2024 — McMap. All rights reserved.