我需要制作一个程序,打开图像,然后才能绘制它。但是我被卡住了,因为它将我的图形返回为null。以下是问题所在的代码块。如果有什么我可以添加整个东西。
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( ) );
}
}
答案 0 :(得分:0)
我猜你不能让图形工作
所以您需要做的是从秋千上获取画布/面板/框架
Canvas canvas = new Canvas();
JFrame frame = new JFrame();
frame.add(canvas);
Graphics g = canvas.getGraphics();