我花了几天时间试图让 Graphics2D 类在我的代码中工作。我的结构是这样的,当注册点击事件时,重新绘制的调用就完成了,但是当它到达调用 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++;
}