完成并运行一个简单的程序后,该程序可让您在单击形状时更改形状的颜色:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel{
int x = 200,y = 200,r = 50;
static Color co = Color.BLUE;
static final JFrame frame = new JFrame();
public static void main(String[] args){
frame.setTitle("Color Change with Mouse Click");
frame.setSize(500,500);
MyPanel pane = new MyPanel();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.setVisible(true);
}
public void Panel(){
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) & (co == Color.GREEN)){
co = Color.BLUE;
repaint();
};
if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) & (co == Color.BLUE)){
co = Color.GREEN;
repaint();
};
}
});
}
Timer timer = new Timer(1, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
Panel();
}
});
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
timer.start();
Panel();
g.setColor(co);
g.fillOval(x-r, y-r, 2*r, 2*r);
repaint();
}
}
我遇到了一个我根本不知道如何解决的问题。JPanel 永远不会在第二次鼠标单击时更新,只会在第一次时更新。我认为添加计时器会解决这个问题,但显然没有。非常感谢您的帮助。
编辑:我根据 Aqua 的建议更改了我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel{
int x = 200,y = 200,r = 50;
static Color co = Color.BLUE;
public static void main(String[] args){
final JFrame frame = new JFrame();
frame.setTitle("Color Change with Mouse Click");
MyPanel pane = new MyPanel();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void panel(){
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) && (co == Color.GREEN)){
co = Color.BLUE;
repaint();
}else if(((e.getX() >= (x-r) && e.getX() < (x+r) && e.getY() >= (y-r) && e.getY() < (y+r))) && (co == Color.BLUE)){
co = Color.GREEN;
repaint();
}else{
repaint();
};
}
});
}
public MyPanel(){
Timer timer = new Timer(20, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
panel();
}
});
timer.start();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(co);
g.fillOval(x-r, y-r, 2*r, 2*r);
repaint();
}
}
并且颜色变化现在有效,但是颜色变化有点不可预测。有时它有延迟,有时没有,有时它完全不会改变。这是我的计时器有问题吗?