drawing on Jframe

后端 未结 4 611
不知归路
不知归路 2020-12-12 00:42

I cannot get this oval to draw on the JFrame.

static JFrame frame = new JFrame(\"New Frame\");
public static void main(String[] args) {
  makeframe();
  pain         


        
4条回答
  •  有刺的猬
    2020-12-12 01:11

    You have created a static method that does not override the paint method. Now others have already pointed out that you need to override paintComponent etc. But for a quick fix you need to do this:

    public class MyFrame extends JFrame {  
       public MyFrame() {
            super("My Frame");
    
            // You can set the content pane of the frame to your custom class.
            setContentPane(new DrawPane());
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(400, 400);
            setVisible(true); 
       }
    
       // Create a component that you can actually draw on.
       class DrawPane extends JPanel {
            public void paintComponent(Graphics g) {
                g.fillRect(20, 20, 100, 200); // Draw on g here e.g.
            }
       }
    
       public static void main(String args[]){
            new MyFrame();
       }
    }
    

    However, as someone else pointed out...drawing on a JFrame is very tricky. Better to draw on a JPanel.

提交回复
热议问题