我正在编写一个用Java绘制线的程序,我使用了PaintComponent,但我不知道为什么它不起作用。到目前为止我写的下面的代码。请帮我。我在其他类中创建了JFrame。
package Paint;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import javax.swing.JPanel;
public class MousePanel extends JPanel {
private boolean start;
private Point last;
private ArrayList<Point> lines;
public MousePanel() {
start = false;
lines = new ArrayList<Point>();
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHandler());
setBackground(Color.white);
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == e.BUTTON1) {
start = true;
last = new Point(e.getX(), e.getY());
lines.add(last);
}
if (e.getButton() == e.BUTTON3)
start = false;
}
}
private class MouseMotionHandler extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
if (start) {
last = new Point(e.getX(), e.getY());
lines.add(last);
repaint();
}
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.black);
// draw all lines
if (lines.size()<2) return;
Point firstPoint = (Point)lines.get(0);
Point secondPoint;
for (int i = 1; i < lines.size(); i++){
secondPoint = (Point) lines.get(i);
g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
firstPoint = secondPoint;
}
}
}
答案 0 :(得分:1)
您需要使用mousePressed
和mouseDragged
代替mouseClicked
和mouseMoved
。我重新考虑了你的代码。希望它有所帮助。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JPanel;
public class MousePanel extends JPanel {
private boolean start;
private Point last;
private ArrayList<Point> lines;
public MousePanel() {
start = false;
lines = new ArrayList<Point>();
MouseHandler mouseHandler = new MouseHandler();
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
setBackground(Color.white);
}
private class MouseHandler extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
start = true;
last = new Point(e.getX(), e.getY());
lines.add(last);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
start = false;
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (start) {
last = new Point(e.getX(), e.getY());
lines.add(last);
repaint();
}
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
// draw all lines
if (lines.size() < 2) {
return;
}
Point firstPoint = (Point) lines.get(0);
Point secondPoint;
for (int i = 1; i < lines.size(); i++) {
secondPoint = (Point) lines.get(i);
g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
firstPoint = secondPoint;
}
}