我的程序中有自定义绘图部分的问题。 我希望用户单击界面,然后在程序绘制一条跟随光标的行时拖动。 但问题是,我几乎看不到它。此外,光标按钮释放后线条不会停留。
自定义绘制线代码:
public void drawTemporaryLine(int x1,int y1,int x2,int y2,ArrayList<Line> lines){
repaint();
g2d = (Graphics2D) getGraphics();
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.black);
for(Line l:lines){
g2d.drawLine(l.getX1(),l.getY1(),l.getX2(),l.getY2());
}
g2d.drawLine(x1, y1, x2, y2);
}
鼠标侦听器代码:
@Override
public void mousePressed(MouseEvent e){
if(draw_on){
x = e.getX();
y = e.getY();
}
}
@Override
public void mouseDragged(MouseEvent e){
if(draw_on){
drawPanel.drawTemporaryLine(x, y, e.getX(), e.getY(),lines);
}
}
@Override
public void mouseReleased(MouseEvent e){
if(draw_on){
lines.add(new Line(x,y,e.getX(),e.getY()));
optionButtons[0].setSelected(false);
draw_on = false;
}
}
有什么办法可以解决吗?感谢。
答案 0 :(得分:1)
尝试覆盖paintComponent
。
我试图自己重现它:
试试这个:)
DrawPanel(扩展JPanel)
private ArrayList<Line> lines = new ArrayList<Line>();
private Line tmpLine = null;
public DrawPanel() {
initComponents();
}
public void drawTemporaryLine(int x1, int y1, int x2, int y2) {
tmpLine = new Line(x1, y1, x2, y2);
}
public void setTemporaryLine(int x1, int y1, int x2, int y2) {
lines.add(new Line(x1, y1, x2, y2));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.black);
for (Line l : lines) {
g2d.drawLine(l.getX1(), l.getY1(), l.getX2(), l.getY2());
}
if (tmpLine != null) {
g2d.drawLine(tmpLine.getX1(), tmpLine.getY1(), tmpLine.getX2(), tmpLine.getY2());
}
}
NewJFrame(扩展JFrame):
private DrawPanel draw = new DrawPanel();
private int x = 0;
private int y = 0;
public NewJFrame() {
initComponents();
setSize(800,600);
add(draw);
draw.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
draw.setTemporaryLine(x, y, evt.getX(), evt.getY());
draw.repaint();
}
public void mousePressed(java.awt.event.MouseEvent evt) {
x = evt.getX();
y = evt.getY();
}
});
draw.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
draw.drawTemporaryLine(x, y, evt.getX(), evt.getY());
draw.repaint();
}
});
}