为什么矩形不会渲染到屏幕

时间:2016-02-06 03:39:17

标签: java swing graphics

public class Rec extends JFrame {    
   public Rec (){       
   JFrame jframe = new JFrame();       
   jframe.setSize(500, 500);
   jframe.setVisible(true); 
 }

public void render (Graphics g){
   g.setColor(Color.red);
   g.fillRect(0,0,50,50);          
}

public static void main(String[] args) {
    Rec frame = new Rec();
    frame.render(g);        
     }    
  }

为什么这不起作用?我知道我可能需要一个paintComponent,如果是这样的话我该如何去做呢?任何帮助都会很棒,谢谢!

2 个答案:

答案 0 :(得分:1)

问题是JFrame中的绘画不是你应该做的。最好(在本例中)将contentpane设置为JPanel,并在JPanel内绘制。

以这个简短的片段为例:

import java.awt.*;
import javax.swing.*;

public class Rec {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame rec = new JFrame();
                rec.setSize(50, 150);
                rec.setContentPane(new JPanel() {
                    @Override
                    protected void paintComponent(Graphics g) {
                        super.paintComponent(g);
                        g.setColor(Color.red);
                        g.fillRect(0, 0, 50, 50);
                    }           
                });
                rec.setVisible(true);
            }
        });
    }
}

结果:

enter image description here

答案 1 :(得分:0)

//May be this is what you are looking for.

public void paintComponent(Graphics g) {
// Create a copy of the passed in Graphics object
Graphics gCopy = g.create();
// Change the properties of gCopy and use it for drawing here
// Dispose the copy of the Graphics object
gCopy.dispose();
}

//or might be this

import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JFrame;

public class DrawingCanvas extends JPanel {
public DrawingCanvas() {
this.setPreferredSize(new Dimension(600, 75));
}
@Override
public void paintComponent(Graphics g) {
// Draw a rectangle
g.fillRect(100, 100, 100, 100);
}
public static void main(String[] args) {
JFrame frame =new JFrame("Drawing");
frame.getContentPane().add(new DrawingCanvas());
frame.pack();
frame.setVisible(true);
}
}