在JPanel中绘制时没有绘制任何内容

时间:2012-04-13 01:27:20

标签: java swing user-interface graphics paintcomponent

我正在尝试在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);  
        }
    }

}

1 个答案:

答案 0 :(得分:4)

你的Rect画得很好,但它非常小!要了解我的意思,请在渲染后显示它的大小:

  Rect rect = new Rect();
  rect.setBorder(BorderFactory.createTitledBorder("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);

  System.out.println(rect.getSize());

你会得到类似的东西:

java.awt.Dimension[width=1,height=1]

意思是它只是1像素乘1像素 - 太小而无法看到。

解决方案是使用适当的布局并为其提供首选大小以便显示。例如,

   public class Rect extends JComponent {

      private static final long serialVersionUID = 1L;
      private static final int PREF_W = 150;
      private static final int PREF_H = 150;

      @Override
      // public void paint(Graphics g) {
      protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         g.setColor(Color.black);
         g.drawRoundRect(10, 10, 100, 100, 20, 20);
      }

      @Override
      public Dimension getPreferredSize() {
         return new Dimension(PREF_W, PREF_H);
      }
   }

另外,使用JComponent的paintComponent方法绘制,而不是绘制方法。