【发布时间】:2014-05-01 20:39:02
【问题描述】:
所以我正在制作一个简单的绘画程序,我有两个面板。第一个面板位于右中,是画布。另一个停靠在右侧,用于按住工具按钮,但目前只有一个清除按钮。问题是当我开始点击画布时,清除按钮被绘制在它上面。知道我缺少什么吗?
public class Paint extends JFrame implements ActionListener {
private Canvas canvas;
private JButton clear;
private JPanel tools;
Paint(){
canvas= new Canvas();
add(canvas,BorderLayout.CENTER);
clear= new JButton("Clear");
clear.addActionListener(this);
tools= new JPanel();
tools.add(clear);
add(tools,BorderLayout.WEST);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==clear){
canvas.clear();
}
}
public static void main(String[] args) {
Paint paint=new Paint();
paint.setSize(1000,800);
paint.setVisible(true);
paint.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
画布:
public class Canvas extends JPanel {
private int x= -10;
private int y= -10;
private boolean clear=false;
Canvas(){
addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e){
x=e.getX();
y=e.getY();
draw();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e){
x=e.getX();
y=e.getY();
draw();
}
});
}
@Override
public void paintComponent(Graphics g){
if(clear){
super.paintComponent(g);
clear=false;
}
else{
g.fillOval(x,y,4,4);
}
}
public void draw(){
this.repaint();
}
public void clear(){
clear=true;
repaint();
}
}
【问题讨论】:
标签: java swing graphics jpanel paint