Paint background of JPanel

前端 未结 5 690
盖世英雄少女心
盖世英雄少女心 2021-01-19 05:16

How can I tell the paint method to draw background on JPanel only and not on the entire JFrame. My JFrame size is bigger than the JPanel. When I try to paint a grid backgrou

5条回答
  •  不要未来只要你来
    2021-01-19 05:33

    camickr is correct. So:

    public class Drawing extends JFrame {
      JPanel drawingPanel;
      ...........
      public Drawing (){
        drawingPanel = new MyPanel();
        drawingPanel.setPreferredSize(new Dimension(600,600));
        add(drawingPanel);
      }
    }
    
    public class MyPanel extends JPanel {
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    
        myBackgroundRoutine(g2);
      }
    }
    

    You need to strictly separate your drawing from different components. Swing is already managing subcomponents, so there is absolutely no need to implement drawings in your Panel in the Frame (calling paintComponents() is a severe error). And you should never override paint(), because only paintComponent() is used in Swing. Don't mix both until you absolutely know what you are doing.

提交回复
热议问题