hnor4
hnor4

Reputation: 11

Adding Paint Component To A JPanel

In my application (using java), a button is pushed and then a panel opens up with a graph on it. To create the graph I am using graphics/paint. However, I am unable to get the graphics to show up. For now, I am just trying to paint a circle (instead of the actual graph). It would be much appreciated if someone could explain what I am doing wrong.

public class SeeProgressHandleClass extends JPanel{

  public SeeProgressHandleClass(JFrame window) {
    this.window = window;
  }

  public void mouseClicked(MouseEvent e) {
    panel = new JPanel();

    fillPanel();

    window.add(panel);      
    panel.setBackground(Color.white);       
    panel.setBounds(50, 40, 1100, 660);
  }

  public static void fillPanel() {
    Graph graph = new Graph();
    panel.add(graph);
 }
}

public class Graph extends JPanel{

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.setBackground(Color.white);
    g.setColor(Color.green);
    g.fillOval(50, 50, 50, 50);
  }

}

Upvotes: 0

Views: 507

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

  • Graph should provide preferredSize hints, which will allow the layout manager to make better determinations about how the component should be displayed. Consider overriding getPreferredSize
  • Don't call this.setBackground(Color.white); inside paintComponent, each time you do this, it will trigger a potential repaint request, which will eventually consume all your CPU cycles. Set this in the constructor
  • You're adding Graph into JPanel and then adding this to the screen ... not sure why, but it's making it more confusing
  • After window.add(panel);, all window.revalidate() and window.repaint() to trigger a new layout and paint pass

Upvotes: 1

Related Questions