【问题标题】:repaint() not calling PaintComponent to use Graphics2Drepaint() 没有调用 PaintComponent 来使用 Graphics2D
【发布时间】:2013-01-27 18:53:36
【问题描述】:

我花了几天时间试图让 Graphics2D 类在我的代码中工作。我的结构是这样的,当一个点击事件被注册时,repaint的调用就完成了,但是当它到达调用repaint()的阶段时,这只会产生一个空指针异常。

调试时一切都按预期工作,而不是从paintComponent方法中调用,但是当尝试使用paintComponent和repaint()正确调用代码以允许Graphics2D类显示每个点的线条时,它不起作用.

我已经包含了我难以开始工作的代码部分。任何帮助都将不胜感激。提前谢谢你。

下面是包含我的 mouseListener 的 GUI 类。

public class GUI extends JPanel implements MouseListener {

private JLabel label;

    public BufferedImage getImg() {
    return img;
    }

    public void mouseClicked(java.awt.event.MouseEvent e) {
    // TODO Auto-generated method stub
    label = new JLabel();

    //set point equal to the location of the mouse click on the image label
    Point b = e.getPoint();

    //place we are going to print the dots
    segmentation.x = b.x; //gets the x coordinate 
    segmentation.y = b.y; //gets the y coordinate

    System.out.println("x = " + segmentation.x);
    System.out.println("y = " + segmentation.y);        

    //set the global img in the segmentation class equal to that of the one in the current tab
    segmentation.setImg(tabbedPane.getSelectedIndex(), getImg());
    segmentation.paintUpdate();
    label = segmentation.getLabel();

    //if i run this line of code the existing label I already have with simply vanish because of the paintComponent method not being called upon properly.
    //tabbedPane.setComponentAt(tabbedPane.getSelectedIndex(), label);
}

这是包含我无法正确调用的 paintComponent 方法的 Segmentation 类。

public class Segmentation extends JLabel {

public int[] xpoints = new int[50];
public int[] ypoints = new int[50];
private int npoints = 0;
public int x;
public int y;
GeneralPath polyline;
Graphics2D g2;
JLabel label;
BufferedImage img;
ImageIcon icon;

public void paintUpdate() {
    repaint();
}

public void setImg(int tabNum, BufferedImage img) {
    this.img = img;
}

public GeneralPath createPath() {

    //      if (npoints > 0) {
    polyline.moveTo(xpoints[0], ypoints[0]);

    for(int i = 1; i < xpoints.length; i++) {
        //add the position of the point to the respective x and y arrays
        polyline.lineTo(xpoints[i], ypoints[i]);        
    }
    //      }
    return polyline;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    System.out.println("we're in the paint component method");

    //set up for the new jlabel
    label = new JLabel();
    label.setIcon(new javax.swing.ImageIcon(img));
    label.setHorizontalAlignment(JLabel.LEFT);
    label.setVerticalAlignment(JLabel.TOP);

    //add the position of the point to the respective x and y arrays
    xpoints[npoints] = x;
    ypoints[npoints] = y;

    if (npoints == 0) {
        JOptionPane.showMessageDialog(null, "Your first point has been added successfully");
    }
    else {
        JOptionPane.showMessageDialog(null, "Your " + npoints + " rd/th" + " point has been added successfully");
    }

    polyline = createPath();

    // Draws the buffered image to the screen.
    g2.drawImage(img, 0, 0, this);

    g2.draw(polyline);

    npoints++;
}

【问题讨论】:

  • 为什么不在 paintComponent 方法中将 Graphics 对象类型转换为 Graphics2D 对象? g2 永远不会在您的代码中初始化。
  • @VishalK 提出了一个很好的观点。您没有正确使用 g2,事实上阅读 Swing 图形教程会让您受益匪浅。

标签: java swing bufferedimage graphics2d paintcomponent


【解决方案1】:

您的 Segmentation 类有两个 JLabel,一个是该类本身的对象,它有一个 paintComponent 覆盖并且可能从未使用过:

public class Segmentation extends JLabel {

另一个名为 label 的 JLabel 由类中的组合持有,该类没有方法覆盖,实际上已使用并且似乎“隐藏”了类的实例:

JLabel label

如果您希望调用paintComponent,您需要使用实际上覆盖该方法的标签对象。

您似乎也在 paintComponent(...) 方法 (??) 中创建组件。永远不要这样做,也不要在此方法中包含程序逻辑。

编辑:
要在图像上绘图,我通常会覆盖 paintComponent 并使用其 Graphics/Graphics2D 对象进行绘制。例如:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.*;

public class DrawOnLabel extends JLabel {
   public static final String GIRAFFE_IMG_URL = "http://upload.wikimedia.org/wikipedia/commons/thumb" +
        "/9/9e/Giraffe_Mikumi_National_Park.jpg/474px-Giraffe_Mikumi_National_Park.jpg";
   private static final Color LINES_COLOR = Color.red;
   private static final Color CURRENT_LINE_COLOR = new Color(255, 200, 200);
   private List<Line2D> lineList = new ArrayList<Line2D>();
   private Line2D currentLine = null;

   public DrawOnLabel() throws IOException {
      URL giraffeUrl = new URL(GIRAFFE_IMG_URL);
      BufferedImage img = ImageIO.read(giraffeUrl);
      ImageIcon icon = new ImageIcon(img);
      setIcon(icon);

      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

      g2.setColor(LINES_COLOR);
      for (Line2D line : lineList) {
         g2.draw(line);
      }
      if (currentLine != null) {
         g2.setColor(CURRENT_LINE_COLOR);
         g2.draw(currentLine);
      }
   }

   private class MyMouseAdapter extends MouseAdapter {
      Point p1 = null;

      @Override
      public void mousePressed(MouseEvent e) {
         p1 = e.getPoint();
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         if (currentLine != null) {
            currentLine = new Line2D.Double(p1, e.getPoint());
            lineList.add(currentLine);
            currentLine = null;
            p1 = null;
            repaint();
         }
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         if (p1 != null) {
            currentLine = new Line2D.Double(p1, e.getPoint());
            repaint();
         }

      }
   }

   private static void createAndShowGui() {
      DrawOnLabel mainPanel = null;
      try {
         mainPanel = new DrawOnLabel();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      JFrame frame = new JFrame("DrawOnLabel");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.setResizable(false);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

【讨论】:

  • 感谢您的回复,但是我有点不确定如何使用覆盖paintComponent 方法的标签对象。对不起,如果这是一个有点愚蠢的问题。
  • @MrBillyUK:你需要去掉 Segmentation 类中的 label 变量和 getLabel() 方法。然后创建一个 Segmentation 实例并将其用作其他类中的 JLabel。但同样,paintComponent(...) 内部不应该有任何程序逻辑,您应该再次将此方法中的 Graphics 对象转换为 Graphics2D 并在那里使用它。
  • 我已经在 GUI 类中全局包含了 Segmentation 类的实例(这是我从 GUI 类中调用 Segmentation 类的方法的方式),但忘记在此示例中包含它,抱歉.但是,我有点不清楚你在 GUI 类中使用 Segmentation 实例作为 JLabel 的意思。你有什么办法可以给我一个例子来说明我如何做到这一点?再次感谢您所做的一切。
  • @MrBillyUK:我确定您确实有一个实例,但是您将这个实例放在 GUI 的什么位置?
  • 我在全局范围内声明它,这样每次触发新的 mouseEvent 时都不会调用它的新实例。
猜你喜欢
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多