Reputation: 15
Bascially I'm having an issue with painting a custom component I made. Whenever repaint() is called the paintComponent() of my Button class is called but nothing shows up in my frame. I also know the component is the right size and is in the right location because I set up a border to check this.
The following is my custom component class:
public class Button extends JComponent {
protected static final Color BUTTON_COLOR = Color.black;
protected Point position;
protected Dimension size;
public Button(int posX, int posY, int width, int height) {
super();
position = new Point(posX, posY);
size = new Dimension(width, height);
setBounds(position.x, position.y, size.width, size.height);
setBorder(BorderFactory.createTitledBorder("Test"));
setOpaque(true);
}
@Override
protected void paintComponent(Graphics g) {
setBounds(position.x, position.y, size.width, size.height);
drawButton(g);
super.paintComponent(g);
}
@Override
public Dimension getPreferredSize() {
return size;
}
public void drawButton(Graphics g) {
selectColor(g, BUTTON_COLOR);
g.fillRect(position.x, position.y, size.width, size.height);
g.setColor(Color.black);
g.drawRect(position.x, position.y, size.width, size.height);
}}
This is the JPanel that my custom component is being added to:
public class MainMenu extends JPanel {
public MainMenu() {
setBackground(Color.BLACK);
setLocation(0,0);
setPreferredSize(new Dimension(800,600));
setDoubleBuffered(true);
setVisible(true);
this.setFocusable(true);
this.requestFocus();
}}
Finally, I add the following components into a MainMenu JPanel:
main_menu.add(new Button(200, 200, 150, 50));
dropdown = new JComboBox<File>() {
@Override
public void paintComponent(Graphics g) {
dropdown.setLocation(new Point(400, 200));
super.paintComponent(g);
}
};
main_menu.add(dropdown);
What's strange is when the repaint() is called on main_menu, the JComboBox is painted but not the Button even though the Button's paintComponent() is called.
Upvotes: 1
Views: 352
Reputation: 285405
Several problems:
setBounds(...)
within a painting method such as paintComponent
. This method is for painting and painting only.drawButton
method should be drawing at 0, 0: g.drawRect(0, 0, size.width, size.height);
setBounds
shouldn't be called regardless. That is the layout managers job. By doing this, you add a whole layer of potential and hard to find bugs.getPreferredSize()
to help set the component's best size (edit -- which you already do, albeit in a very simple fashion).super.paintComponent(g)
should probably be called first in the paintComponent override.Upvotes: 3