问题:我正在尝试根据用户操作使用新的绘画对象更新画布。画布剂量得到更新。
我所做的:用户与 DnD 动作交互,可传输对象到达画布,调用我创建的更新图形方法。该方法仅使用已经创建的图形 2d 对象并使用它绘制图像。我检查了 DnD 操作,该对象在画布类中正确接收,我能够使用 System.out.println 将它们打印出来。
一个与我的功能相似的示例代码,
油漆类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class PaintPanel extends JPanel{
private Graphics2D drawImage;
public PaintPanel()
{
}
@Override
public void paint(Graphics g) {
drawImage = (Graphics2D) g;
drawImage.setColor(Color.WHITE);
drawImage.fillRect(0, 0, getWidth(), getHeight());
}
public void updateGraphics(int length,int width)
{
drawImage.setColor(Color.black);
drawImage.drawRect(100, 150, length, width);
repaint();
}
}
大型机类:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainPaint extends JFrame{
public MainPaint()
{
setTitle("test paint");
setSize(400,400);
setLayout(new BorderLayout());
final PaintPanel paintPan = new PaintPanel();
JButton testButon = new JButton("Display shape");
add(paintPan,BorderLayout.CENTER);
add(testButon,BorderLayout.PAGE_END);
testButon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
paintPan.updateGraphics(50,50);
repaint();
}
});
setVisible(true);
}
public static void main(String[] args)
{
new MainPaint();
}
}