我是java Swing的初学者。 我的代码是这样的:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class LineDrawing extends JComponent
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
int startX = 0;
int startY = 0;
int endX = 0;
int endY = 0;
addMouseListener(new MouseListener(){
@Override
public void mousePressed(MouseEvent e)
{
startX = e.getXOnScreen();
startY = e.getYOnScreen();
}
@Override
public void mouseReleased(MouseEvent e)
{
endX = e.getXOnScreen();
endY = e.getYOnScreen();
Draw d = new Draw();
d.lineDraw(startX,startY,endX,endY);
panel.add(d);
frame.add(panel);
}
@Override
public void mouseClicked(MouseEvent e){}
@Override
public void mouseEntered(MouseEvent e){}
@Override
public void mouseExited(MouseEvent e){}
});
addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent e)
{
endX = e.getXOnScreen();
endY = e.getYOnScreen();
}
@Override
public void mouseMoved(MouseEvent e){}
});
frame.setSize(500,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class Draw extends JPanel
{
public void lineDraw(int x1,int y1,int x2,int y2)
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(x1,y1,x2,y2);
}
}
}
}
当我执行此操作时,它给了我这个错误:
如何增强此代码并解决上述错误。
我也见过其他代码,但paintComponent中出现了错误。
如果我在paintComponent之前放置@Override ...它会出现此错误:
1)';'声明遗失。 2)非法开始表达。
答案 0 :(得分:2)
与BackSlash评论一样,您无法在现有内容中声明方法。
试试这个:
public class Draw extends JPanel {
private int[] line = new int[4];
public void lineDraw(int x1,int y1,int x2,int y2) {
line[0] = x1;
line[1] = y1;
line[2] = x2;
line[3] = y2;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(line[0],line[1],line[2],line[3]);
}
}
要绘制多行,您需要将行数组添加到另一个数据结构(如ArrayList)中,并在paintComponent方法中迭代此列表并绘制所有内容。