开发者

Placing drawing on JPanel

My program have 3 classes. 1) main, 2) frame, 3) drawingBoard. The logic of my program is that, a new drawing will be displayed every times user click on New pattern button (and this working fine).

1st class - main method

public class mainPage {
   public static void main(String[]args){
     JFrame appFrame = new Frame();
     appFrame.setVisible(true); 
     appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/
   }
}

2nd class - describe the layout (I use Grid Bag Layout)

public class Frame extends JFrame implements ActionListener {
  public Frame (){
   GridBagLayout m = new GridBagLayout();
   Container c = (Container)getContentPane();
   c.setLayout (m);
   GridBagConstraints con;

   JButton bPattern = new JButton("New Pattern");
   ....
   bPattern.addActionListener(this);

   JPanel pDraw = new JPanel();        
   .....
   pDraw.add(new drawingBoard()); //drawing will be placed in this panel
 }

 public void actionPerformed(ActionEvent e) {
   repaint();        
 }

}

3rd class - run drawing functions e.g. paintComponent (), etc.

public class drawingBoard extends JPanel {
  public drawingBoard(){}
  public void paintComponent(Graphic g){}
  ....
  }

The problem is that, when I look on the console, it seems that even though the user did not click on the button, the program call the class 'drawingBoard' and repaint. The paint component is in the 3rd class (drawingBoard). Although this seem not to give me a problem (e.g. no drawing displayed on the panel unless the user click the button开发者_运维技巧), I am just curious how this happened. is that because I wrote this code at FRAME class (). My intention to write this code is to make sure the drawing should be place in this specific panel (I have 3 panels) but not to call the 3rd class unless the button has been clicked.

JPanel pDraw = new JPanel();        
pDraw.add(new drawingBoard()); //place drawing here


The repaint method (and subsequently, the paintComponent method) is not only called by the JFrame but also by Swing itself as well, when there needs to be a repaint of the contents of the JPanel.

The Painting in AWT and Swing article is a good place to start to get information on how painting works.

In this case, the repaint method is being called by events which the article calls System-triggered Painting:

In a system-triggered painting operation, the system requests a component to render its contents, usually for one of the following reasons:

  • The component is first made visible on the screen.
  • The component is resized.
  • The component has damage that needs to be repaired. (For example, something that previously obscured the component has moved, and a previously obscured portion of the component has become exposed).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜