我有一个Java绘图程序,它使用自定义JPanel进行绘制。当点击JPanel时会画一个小椭圆(或圆圈,如果你愿意的话),每当你点击另一个地方时,椭圆会消失。坐标也会更新,但椭圆不会停留,它会移动到用户点击下一个位置... 这是自定义JPanel的代码:
int xCord, yCord;
public class PaintPanel extends JPanel implements MouseListener {
// default serial whatever...
private static final long serialVersionUID = -6514297510194472060L;
// initial values
int xCord = -10;
int yCord = -10;
public PaintPanel() {
addMouseListener(this);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(ProgramUI.currentColor);
g.fillOval(xCord, yCord, 8, 8);
repaint();
}
@Override
public void mouseClicked(MouseEvent m) {
}
@Override
public void mouseEntered(MouseEvent m) {
}
@Override
public void mouseExited(MouseEvent m) {
}
@Override
public void mousePressed(MouseEvent m) {
if (paintPanel.contains(m.getPoint())) {
xCord = m.getX();
yCord = m.getY();
System.out.println("x: " + xCord + " y: " + yCord);
}
}
@Override
public void mouseReleased(MouseEvent m) {
}
}
我需要握住鼠标来连续画椭圆形,直到鼠标按钮松开。这里唯一的问题是鼠标椭圆更新,但不保存它的原始位置。我该如何解决?
答案 0 :(得分:5)
只绘制了一个椭圆,因为在fillOval
方法中只有一个paintComponent
语句绘制了一个椭圆,因此语句
super.paintComponent(g);
会在调用repaint
后清除任何先前的绘画。
要绘制多个椭圆,您可以按Custom Painting Approaches
中所述的List<Point>
绘制组件
请勿在{{1}}内致电repaint
。这会产生无限循环并降低性能。如果需要定期更新,请从Swing Timer的paintComponent
调用repaint
。
答案 1 :(得分:0)
这是因为组件重新绘制自己,为了使更改永久化,您应该拍摄jpanel的图像并在每次完成绘图后将其设置为背景...
答案 2 :(得分:0)
您只是在绘制用户每次点击的 last 位置。相反,您需要收集过去的点击并每次都绘制它们。
此代码将执行您想要的操作:
package com.sandbox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
public class SwingSandbox {
public static void main(String[] args) {
JFrame frame = buildFrame();
frame.add(new PaintPanel());
}
public static class PaintPanel extends JPanel implements MouseListener {
// default serial whatever...
private static final long serialVersionUID = -6514297510194472060L;
ArrayList<Point> points = new ArrayList<Point>();
public PaintPanel() {
addMouseListener(this);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(250));
for (Point point : points) {
g.fillOval(point.x, point.y, 8, 8);
}
repaint();
}
@Override
public void mouseClicked(MouseEvent m) {
}
@Override
public void mouseEntered(MouseEvent m) {
}
@Override
public void mouseExited(MouseEvent m) {
}
@Override
public void mousePressed(MouseEvent m) {
if (this.contains(m.getPoint())) {
points.add(m.getPoint());
}
}
@Override
public void mouseReleased(MouseEvent m) {
}
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}