drawing on Jframe

后端 未结 4 612
不知归路
不知归路 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:08

    You need to Override an exist paint method that actually up to dates your Frame. In your case you just created your custom new method that is not called by Frame default.

    So change your method to this:

    public void paint(Graphics g){
    
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 01:24

    Several items come to mind:

    1. Never override paint(), do paintComponent() instead
    2. Why are you drawing on a JFrame directly? Why not extends JComponent (or JPanel) and draw on that instead? it provides more flexibility
    3. What's the purpose of that JLabel? If it sits on top of the JFrame and covers the entire thing then your painting will be hidden behind the label.
    4. The painting code shouldn't rely on the x,y values passed in paint() to determine the drawing routine's start point. paint() is used to paint a section of the component. Draw the oval on the canvas where you want it.

    Also, you're not seeing the JLabel because the paint() method is responsible for drawing the component itself as well as child components. Overriding paint() is evil =)

    0 讨论(0)
  • 2020-12-12 01:28

    You are overriding the wrong paint() method, you should override the method named paintComponent like this:

    @Override 
    public void paintComponent(Graphics g)
    
    0 讨论(0)
提交回复
热议问题