题目:
·编程实现以下功能:
? ? ? ? 界面如下图所示;
????????当点击不同的按钮时,圆的填充颜色会随之改变;
????????用鼠标点击圆内部时,圆的 填充颜色会依照”面板背景色-红色-绿色-蓝色”循环改变;
????????鼠标移到圆内时,光标变成十字形;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
public class Circle extends JFrame {
public static void main(String[] args) {
JFrame jFrame = new Circle();
jFrame.setDefaultCloseOperation(3);
jFrame.setVisible(true);
}
public Circle() {
this.setTitle("change color");
this.setSize(500, 500);
add(new jPanel());
}
}
class jPanel extends JPanel {
private Ellipse2D rec;
private int num = 0;
JButton B01 = new JButton("Green");
JButton B02 = new JButton("Blue");
JButton B03 = new JButton("Red");
public jPanel() {
MouseClickListener mcl = new MouseClickListener();
MouseCursorListener mcll = new MouseCursorListener();
this.addMouseListener(mcl);
this.addMouseMotionListener(mcll);
ButtonActionListener bal = new ButtonActionListener();
B01.addActionListener(bal);
B02.addActionListener(bal);
B03.addActionListener(bal);
this.add(B01);
this.add(B02);
this.add(B03);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
rec = new Ellipse2D.Double(140, 140, 200, 200);
if (num % 4 == 0) {
g2.setPaint(Color.BLACK);
}
if (num % 4 == 1) {
g2.setPaint(Color.GREEN);
g2.fill(rec);
}
if (num % 4 == 2) {
g2.setPaint(Color.BLUE);
g2.fill(rec);
}
if (num % 4 == 3) {
g2.setPaint(Color.RED);
g2.fill(rec);
}
g2.draw(rec);
g2.setPaint(Color.BLACK);
g2.draw(rec);
repaint();
}
public Boolean exist(Point2D p) {
if (rec.contains(p)) {
return true;
}
return false;
}
class MouseClickListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
Point2D p = e.getPoint();
if (exist(p)) {
num++;
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
class MouseCursorListener implements MouseMotionListener {
@Override
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent me) {
Point2D p = me.getPoint();
if (exist(p)) {
setCursor(Cursor.getPredefinedCursor(
Cursor.CROSSHAIR_CURSOR));
} else
setCursor(Cursor.getDefaultCursor());
}
}
class ButtonActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == B01) {
num = 1;
} else if (obj == B02) {
num = 2;
} else if (obj == B03) {
num = 3;
}
}
}
}