簡體   English   中英

在JPanel中繪制時未繪制任何內容

[英]Nothing drawn when drawing in a JPanel

我正在嘗試在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);  
        }
    }

}

您的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方法)進行繪制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM