你好,先谢谢我们需要通过鼠标点击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);
}
});
}
}
答案 0 :(得分:1)
关于坐标的打印:声明内部类如下
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());
}
每次单击面板时,都会打印出坐标。