当我运行我的代码时,只有在JPanel
的左上角单击鼠标时才会显示一个矩形。当它出现时,它会变形变形。如果我将fillRect
更改为fillOval
,它根本不显示。我的目标是在点击鼠标时在鼠标位置填充一个圆圈。我的代码是:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PaintProgram {
JFrame frame;
JPanel panel;
Point p;
int x;
int y;
int diameter;
public PaintProgram(){
frame = new JFrame();
frame.setSize(500,500);
panel = new JPanel();
diameter = 100;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.addMouseListener(new MListener());
panel.add(new DrawCircle());
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args){
PaintProgram p = new PaintProgram();
}
class UBListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent a){
}
}
class MListener implements MouseListener{
public void mousePressed(MouseEvent e){
p = panel.getMousePosition();
x = (int) p.getX();
y = (int) p.getY();
panel.add(new DrawCircle());
frame.repaint();
frame.revalidate();
System.out.println(x + "," + y);
}
public void mouseReleased(MouseEvent e){
}
public void mouseClicked(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
}
class DrawCircle extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(x,y,diameter,diameter);
System.out.println(x + "," + y);
}
}
}
我认为您的代码存在一些问题。首先,您在PaintProgram
中定义的JPanel不是必需的,并且在您的代码中导致了一些问题。基本上我已经切换到使用JFrame几乎所有东西。接下来,我不认为你想在DrawCircle()
中创建一个新的PaintProgram
,只需点击鼠标即可。
以下代码适用于我(每当你点击时在你的光标周围绘制一个圆圈,我认为这就是你想要的)。我做了一些我没有提到的改动,所以随便提问。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PaintProgram {
JFrame frame;
Point p;
int x;
int y;
int diameter;
public PaintProgram(){
frame = new JFrame();
frame.setSize(500,500);
diameter = 100;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(new MListener());
frame.setVisible(true);
}
public static void main(String[] args){
PaintProgram p = new PaintProgram();
}
class UBListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent a){
}
}
class MListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e){
p = frame.getMousePosition();
x = (int) p.getX();
y = (int) p.getY();
frame.add(new DrawCircle());
frame.repaint();
frame.revalidate();
System.out.println(x + "," + y);
}
}
class DrawCircle extends JPanel{
@Override
public void paintComponent(Graphics g){
g.setColor(Color.orange);
g.fillOval(x - 56, y - 77, diameter, diameter);
System.out.println(x + "," + y);
}
}
}