我的工作是在单击特定按钮时将背景颜色更改为按钮上提到的颜色。但是当单击按钮时,我的 JApplet 似乎没有显示颜色的任何变化。
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class ColorChange extends JApplet implements MouseListener{
Color c = null;
JButton b1;
JButton b2;
JButton b3;
JFrame f;
JPanel p;
public void init()
{
frame();
}
private void frame() {
// TODO Auto-generated method stub
f = new JFrame();
f.setSize(200,200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
b1= new JButton("RED");
b1.addMouseListener(this);
b2 = new JButton("BLUE");
b2.addMouseListener(this);
b3 =new JButton("GREEN");
b3.addMouseListener(this);
p.setLayout(new FlowLayout());
p.add(b1);
p.add(b2);
p.add(b3);
f.add(p);
f.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource().equals(b1))
c = Color.red;
else if(arg0.getSource().equals(b2))
c = Color.blue;
else if(arg0.getSource().equals(b3))
c =Color.green;
else
c = Color.yellow;
repaint();
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void paint()
{
f.setBackground(c);
}
}