在另一个函数中声明的画布上绘制java
我有一个应用程序,它有一个swing用户界面类,它有一些按钮,可以将变量发送到canvas类,就像这样
public class createWindow extends JFrame implements ActionListener
{
createCanvas canvas = new createCanvas(10, 10);
JPanel mainPanel = new JPanel();
public createWindow()
{
mainPanel.add(canvas, BorderLayout.CENTER);
}
}
createCanvas是一个声明paintComponent的类
public class createCanvas extends JPanel
{
int xValue;
int yValue;
int xCoordinate;
int yCoordinate;
public createCanvas(int x, int y)
{
xValue = x;
yValue = y;
}
public void setXCoordinate(int x)
{
xCoordinate = x;
}
public void setYCoordinate(int y)
{
yCoordinate = y;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawGrid(g, this.xValue, this.yValue);
g.fillArc(xCoordinate, yCoordinate, 6, 6, 0, 360);
}
public drawGrid(Graphics g, int xLength, int yLength)
{
//creates a grid that is xLength x yLength
}
}
然而,我也有一个选择的对象,我想有一个。函数,该函数可以在createCanvas中使用paintComponent。 当然,问题是,当我需要在网格上绘制节点时,我可以设置坐标,但是如何在createWindow中声明的画布上显示节点
public class Node()
{
int xCoordinate;
int yCoordinate;
//Suitable constructors, sets, gets
public void draw()
{
createCanvas canvas = new createCanvas();
canvas.setXCoordinate(this.xCoordinate);
canvas.setYCoordinate(this.yCoordinate);
canvas.repaint();
}
}
因此,我想知道是否有一种方法可以让我在createWindow中保存画布上绘制的内容,以及在Object类中绘制的内容
谢谢
# 1 楼答案
您要做的是让对象中的
draw
方法接受一个Graphics
参数。这个Graphics
对象将与paintComponent
方法中的Graphics
上下文相同。可以在JPanel
类中创建对象。像这样的然后在你的
JPanel
课上您可以在
Circle
类中为x
和y
设置一个setter
。你应该在JPanel
类的某个地方更改它们,然后调用repaint()
。你可以按一个键来移动它,也可以用java.util.Timer
来设置动画。比如用Timer
用key binding
用button press