2

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

}
4

1 回答 1

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 方法而不是它的paint 方法进行绘制。

于 2012-04-13T02:01:10.020 回答