java - 在 Jframe 上绘图

标签 java swing

我无法在 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();
}

框架显示但未在其中绘制任何内容。我在这里做错了什么?

最佳答案

您已经创建了一个静态方法,它不会覆盖 paint 方法。现在其他人已经指出您需要覆盖 paintComponent 等。但是为了快速修复,您需要这样做:

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();
   }
}

但是,正如其他人指出的那样...在 JFrame 上绘图非常棘手。最好在 JPanel 上绘制。

关于java - 在 Jframe 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2134840/

相关文章:

java - 手动关闭java swing窗口

java - SwingUtilites : how to return values from another thread in Java?

java - 使用流总结列表

java - Java Swing 不显示重复样式

java - Java中的概率

java - 为什么这不转换所有实例?

java - JTable 上的边距为 1px 边框

java - JTable regexFilter right int 来过滤第一列?

java - 为 JFrame 制作自定义图标

java - Mahout - 如何取消设置 Mahout_local 以在 Hadoop 文件系统中运行?