我有一个基本的抽屉应用程序,当我绘制一个新行时,我必须删除最后一行。这是我的代码:
public class DrawLine extends JFrame implements MouseListener {
private JPanel contentPane;
private int x0, y0;
private MyLine ml;
private JPanel panel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DrawLine frame = new DrawLine();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DrawLine() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.addMouseListener(this);;
}
@Override
public void mousePressed(MouseEvent e) {
for (Component c : panel.getComponents()) {
panel.remove(c);
}
x0 = e.getX();
y0 = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
if(ml == null){
ml = new MyLine(x0, y0, e.getX(), e.getY());
panel.add(ml);
}
else{
ml = new MyLine(x0, y0, e.getX(), e.getY());
ml.paintcomponent(getGraphics());
}
}
}
这也是我的Line类:
public class MyLine extends JComponent{
private int x0, y0, x1, y1;
public MyLine(int x0, int y0, int x1, int y1){
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
}
public void paintcomponent(Graphics gr){
super.paintComponent(gr);
gr.drawLine(x0, y0, x1, y1);
}
}
在mousePressed事件监听器中,我使用for循环,其中所有组件都从面板中删除,但它不起作用。我也尝试使用panel.removeAll(),但没有成功。