这段代码完全适用于我之前和以后使用的所有其他电脑,但出于某些原因,当我在电脑上运行它时,它有一个奇怪的错误。
当我点击一个正方形然后点击一个圆圈时,我刚刚点击的正方形的新颜色将成为我点击的圆圈的背景颜色,而不是圆圈的填充而是实际的背景
同样,当第一次点击一个圆圈时,我点击的圆圈右侧会出现一个蓝色圆圈的轮廓。
我需要帮助,以便我可以在计算机上编码,并且能够完成我的课程。 我已经在使用1.6和1.7的计算机之间切换并更改它们以便它们工作,一切都很好。所以从我所看到的只是我的电脑,我已经更新了所有的Java程序(JDK,我的显卡的驱动程序,eclipse)我似乎无法弄明白。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.awt.Graphics2D;
import java.util.Random;
import javax.swing.*;
public class Part2 extends JFrame {
public static void main(String[] args) {
Part2 window = new Part2("Shape Colour");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Part2(String title) {
super(title);
//adds the circle and square objects to the new Panel
JPanel all = new JPanel();
this.setContentPane(all);
this.setSize(900, 200);
this.setResizable(true);
all.setLayout(new GridLayout());
all.add(new Circle());
all.add(new Rectangle());
all.add(new Circle());
all.add(new Rectangle());
all.add(new Circle());
setVisible(true);
}
abstract class shape extends JPanel {
Random random = new Random();
RectangularShape shape;
Color color;
//creates a shape of random "colour" (notice the "u"), and adds a MouseListener
public shape() {
super();
//this.setSize();
randomColor();
this.addMouseListener(new ShapeListener(this));
}
//Decided how to paint the shape, and fill it with one colour
//names each shape "thing"
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D thing = (Graphics2D) g;
thing.setColor(color);
thing.fill(shape);
}
//makes a random colour form all possible combinations of colour
private void randomColor() {
this.color = new Color(random.nextInt(256), random.nextInt(256),random.nextInt(256));
}
class ShapeListener implements MouseListener {
JPanel ShapePanel;
int mouseX;
int mouseY;
//shapePanel constructor
public ShapeListener(JPanel shapePanel) {
this.ShapePanel = shapePanel;
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
//gets the mouse coordinates
mouseX = e.getX();
mouseY = e.getY();
//if you click within the area of the shape that is at those coordinates then it will repaint, a random colour
if (shape.contains(mouseX, mouseY)) {
randomColor();
ShapePanel.repaint();
}
}
}
}
//method for creating a circle
class Circle extends shape {
public Circle() {
super();
this.shape = new Ellipse2D.Double(10, 10, 150, 150);
}
}
//and a square
class Rectangle extends shape {
public Rectangle() {
super();
this.shape = new Rectangle2D.Double(10, 10, 150, 150);
}
}
}