gpt4 book ai didi

java - java中Graphics2D中的鼠标点击事件

转载 作者:行者123 更新时间:2023-12-01 11:49:42 25 4
gpt4 key购买 nike

您好,提前谢谢大家,我需要通过鼠标单击 Graphics2D 的绘图面板来找到 X 和 y 坐标值,并且我需要获取坐标的字符串值,随机改变坐标的颜色。

package com.zetcode;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

private void doDrawing(Graphics g) {

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(10, 15, 90, 60);
g2d.drawRect(130, 15, 90, 60);
g2d.drawRect(250, 15, 90, 60);
g2d.drawRect(10, 105, 90, 60);
g2d.drawRect(130, 105, 90, 60);
g2d.drawRect(250, 105, 90, 60);
g2d.drawRect(10, 195, 90, 60);
g2d.drawRect(130, 195, 90, 60);
g2d.drawRect(250, 195, 90, 60);

g2d.setColor(new Color(125, 167, 116));
g2d.fillRect(10, 15, 90, 60);

g2d.setColor(new Color(42, 179, 231));
g2d.fillRect(130, 15, 90, 60);

g2d.setColor(new Color(70, 67, 123));
g2d.fillRect(250, 15, 90, 60);

g2d.setColor(new Color(130, 100, 84));
g2d.fillRect(10, 105, 90, 60);

g2d.setColor(new Color(252, 211, 61));
g2d.fillRect(130, 105, 90, 60);

g2d.setColor(new Color(241, 98, 69));
g2d.fillRect(250, 105, 90, 60);

g2d.setColor(new Color(217, 146, 54));
g2d.fillRect(10, 195, 90, 60);

g2d.setColor(new Color(63, 121, 186));
g2d.fillRect(130, 195, 90, 60);

g2d.setColor(new Color(31, 21, 1));
g2d.fillRect(250, 195, 90, 60);




}


public void mouseClicked(MouseEvent me) {
int x1 = me.getX();
int y1 = me.getY();
System.out.println(x1);
JOptionPane.showMessageDialog(this, x1);
JOptionPane.showMessageDialog(this, y1);
//System.out.println(y1);
}
@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
doDrawing(g);

}
}

public class RectanglesExample extends JFrame {



public RectanglesExample() {
initUI();
}

public final void initUI() {

DrawPanel dpnl = new DrawPanel();
add(dpnl);

setSize(360, 300);
setTitle("Rectangles");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
RectanglesExample ex = new RectanglesExample();
ex.setVisible(true);
}
});
}
}

最佳答案

关于坐标的打印:声明一个内部类如下

    public class MyMouseListener extends MouseAdapter{


@Override
public void mouseClicked(MouseEvent e) {
int x1 = e.getX();
int y1 = e.getY();
System.out.println(x1);
System.out.println(y1);
repaint();

}
}

并添加一个注册MyMouseListener

的构造函数
   public DrawPanel(){
this.addMouseListener(new MyMouseListener());
}

每次单击面板时,这都会打印坐标。

关于java - java中Graphics2D中的鼠标点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28898403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com