我正在研究一个简单的 object drawing使用 Java 中的 Swing 编写程序。 我的程序应该简单地根据单击时的按钮绘制形状,并用鼠标移动任何形状。我有四个按钮,可以在屏幕上绘制矩形、圆形和正方形。到目前为止,当您单击按钮时,我确实成功地绘制了形状。但我想移动屏幕上的形状,但没有成功。
问题是这样的:当我单击圆形形状并用鼠标拖动它时,它会清除所有屏幕,并且屏幕上会出现注释。
还有,当我点击清除按钮时,有没有办法清除所有屏幕?
谢谢?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintProject extends JComponent implements ActionListener,
MouseMotionListener {
private int CircleX=0;
private int CircleY=0;
private int RectX=100;
private int RectY=100;
private int SquareX=300;
private int SquareY=200;
public static void main(String[] args) {
JFrame frame = new JFrame("NEW PAINT PROGRAME!");
JButton CircleButton = new JButton("Circle");
CircleButton.setActionCommand("Circle");
JButton RectangleButton = new JButton("Rectangle");
RectangleButton.setActionCommand("Rectangle");
JButton SquareButton = new JButton("Square");
SquareButton.setActionCommand("Square");
PaintProject paint = new PaintProject();
CircleButton.addActionListener(paint);
RectangleButton.addActionListener(paint);
SquareButton.addActionListener(paint);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(paint);
frame.add(CircleButton);
frame.add(RectangleButton);
frame.add(SquareButton);
frame.addMouseMotionListener(paint);
frame.pack();
frame.setVisible(true);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
private void drawCircle() {
Graphics g = this.getGraphics();
g.setColor(Color.red);
g.fillOval(CircleX, CircleY, 100, 100);
}
private void drawRectangle() {
Graphics g = this.getGraphics();
g.setColor(Color.green);
g.fillRect(RectX, RectY, 100, 300);
}
private void drawSquare() {
Graphics g = this.getGraphics();
g.setColor(Color.blue);
g.fillRect(SquareX, SquareY, 100, 100);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Circle")) {
drawCircle();
}
else if (command.equals("Rectangle")) {
drawRectangle();
}
else if (command.equals("Square")) {
drawSquare();
}
}
@Override
public void mouseDragged(MouseEvent e) {
CircleX=e.getX();
CircleY=e.getY();
repaint();
}
}
最佳答案
如上所述here和 here , getGraphics()
不是如何执行custom painting在 Swing 中。相反,覆盖 paintComponent()
呈现所需的内容。看起来您想使用鼠标拖动形状。显示了移动选定对象的基本方法 here ;替换你的fillXxx()
调用 drawString()
显示在那里。对于多个形状,请使用 List<Shape>
;那么clear命令就变成简单的List::clear
。引用了完整的例子here ;它具有可移动、可选择、可调整大小、通过边缘连接的彩色节点。
关于Java Swing 用鼠标移动形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292576/