我正在尝试使用MouseClick单击某个位置并更改该位置的颜色,但不幸的是我无法使其正常工作。任何人都可以通过“不放弃代码”来帮助我吗?这是代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.imageio.*;
import java.util.*;
import java.net.URL;
import java.awt.image.*;
import java.awt.Toolkit.*;

public class Project extends JPanel
implements KeyListener, MouseListener, MouseMotionListener {
  char shape = 'r';
  int x=0;
  int y=0;

  boolean levels = false;

  public Project() {
    setFocusable(true);
    addKeyListener(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    setSize(400,400);
  }

  public void paintComponent(Graphics g) {
    Dimension d = getSize();
    g.setColor(getBackground());
    g.fillRect(0,0,d.width,d.height);
    setBackground (Color.cyan);
    g.setColor(Color.black);
    g.drawString("X: " + x + " Y: " + y, 5,10);

    //Levels
    g.setColor(Color.black);
    g.fillRect(300,165,100,50);
    g.setFont(new Font("default", Font.BOLD, 30));
    g.setColor(Color.cyan);
    g.drawString("Levels", 300, 200);

    if (x >= 300 && x <= 402 && y >= 165 && y <= 218 && levels) {
      g.setColor(Color.red);
    }
    //Levels
  }

  public void keyTyped(KeyEvent e) {}
  public void keyPressed(KeyEvent e) {
    shape = e.getKeyChar();
    repaint();
  }

  public void keyReleased(KeyEvent e) {}
  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) {
    if (x >= 300 && x <= 402 && y >= 165 && y <= 218) {
       levels= true;
    }
    repaint();
  }

  public void mouseDragged(MouseEvent e) {}

  public void mouseMoved(MouseEvent e) {
     x=e.getX();
     y=e.getY();
     repaint();
  }

  public static void main(String args[]) {
    JFrame f = new JFrame("Project");
    Project dc = new Project();
    f.getContentPane().add(dc);
    f.setSize(1200,775);
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e ){
        System.exit(0);
      }
    });
    f.setVisible(true);
  }
}

最佳答案

将color变量作为类成员放置,以便所有成员都可以使用它。

public class Project .... {

    Color color = Color.RED;

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        ...
        g.setColor(color);
        ...
    }

    public void mouseClicked(MouseEvent e){
        color = Color.BLUE;
        repaint();
    }
}

关于java - 如何使MouseClick发生?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19942293/

10-11 21:30