Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I cannot get this oval to draw on the JFrame.

static JFrame frame = new JFrame("New Frame");
public static void main(String[] args) {
  makeframe();
  paint(10,10,30,30);
}

//make frame
public static void makeframe(){
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  JLabel emptyLabel = new JLabel("");
  emptyLabel.setPreferredSize(new Dimension(375, 300));
  frame.getContentPane().add(emptyLabel , BorderLayout.CENTER);
  frame.pack();
  frame.setVisible(true); 
}

// draw oval 
public static void paint(int x,int y,int XSIZE,int YSIZE) {
  Graphics g = frame.getGraphics();
  g.setColor(Color.red);
  g.fillOval(x, y, XSIZE, YSIZE);
  g.dispose();
}

The frame displays but nothing is drawn in it. What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...