我正在尝试在 JPanel 中绘制一个矩形,但是它不会显示出来,但是它可以在框架中使用。
如果你取消注释 //frame.getContentPane().add(rect); //将绘制如果它在框架和注释 frame.getContentPane().add(panel); // 但不在面板中,矩形将绘制。
谢谢您的帮助。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawingRect{
public static void main(String[] args) {
DrawingRect d = new DrawingRect();
}
public DrawingRect(){
JFrame frame = new JFrame("Drawing a rect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension (500,500));
Rect rect = new Rect();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension (500,500));
panel.setVisible(true);
panel.add(rect);
//frame.getContentPane().add(rect); //Will draw if its in the frame
frame.getContentPane().add(panel); // but not in the panel
frame.pack();
frame.setVisible(true);
panel.repaint();
frame.repaint();
}
public class Rect extends JComponent{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawRoundRect(10, 10, 100, 100, 20, 20);
}
}
}