【发布时间】:2015-06-11 07:40:24
【问题描述】:
我正在制作一个程序,当用户按下鼠标然后再次按下时改变矩形的颜色
按下默认颜色发生我在jpanel上用
油漆组件方法的帮助。我使用鼠标适配器编写了鼠标按下方法。但是如何制作
当用户在矩形上按下鼠标时,将矩形颜色变为红色的功能在再次按下此矩形时也会显示默认颜色。这是图片
代码:
public class A extends JPanel{
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.BLACK);
g.fillRect(6, 10, 66, 70);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
}
});
}
}
主要:
public class Main {
public static void main(String[] args) {
JFrame obj = new JFrame();
A object = new A();
obj.add(object);
obj.setSize(450, 400);
obj.setResizable(false);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setLocationRelativeTo(null);
obj.setVisible(true);
}
}
【问题讨论】:
-
看起来很不对劲?为什么要在paintComponent 中添加mouseListener?
-
@Gosu 因为如果我错了矩形会在paintComponent上绘制,那么在哪里添加MouseListener