我需要制作一个程序来打开一个图像,然后可以在它上面绘图。但是我被卡住了,因为它将我的图形返回为空。这是问题所在的代码块。如果有的话,我可以添加整个内容。
public void paintComponent(Graphics gd) {
// super.paintComponent(g);
super.paintComponent(gd);
//gd.drawString("This is my custom Panel!",10,20);
pencil(gd);
}
public void pencil(Graphics gd){
Graphics2D g2 = (Graphics2D)gd;
System.out.println("g2 " + g2 + "method was called");
//g2.setColor(Color.yellow);
//Line2D line = new Line2D();
g2.drawLine(x1,y1,x2,y2);
//System.out.println("pencil");
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == open){
int returnVal = fc.showOpenDialog(Lab3.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
img=ImageIO.read(file);
ImageIcon icon=new ImageIcon(img); // ADDED
image.setIcon(icon); // ADDED
Dimension imageSize = new Dimension(icon.getIconWidth(),icon.getIconHeight()); // ADDED
image.setPreferredSize(imageSize); // ADDED
image.add(hbar, BorderLayout.SOUTH);
image.add(vbar, BorderLayout.EAST);
image.revalidate(); // ADDED
image.repaint(); // ADDED
Graphics gd = image.getGraphics();
}
catch(IOException e1) {}
}
}
if (e.getSource() == pencil){
try{
System.out.println("g2" + g2);
//pencil();
pencil(g2);
//g2.draw(new Ellipse2D.Double(0, 100, 30, 30));
//g2.drawRectanlge(100,100,200,200);
}
catch ( Exception err1 ) {
System.out.println( err1.getMessage( ) );
}
}