Can';t在JavaSwing中从JPanel中删除JComponents
我有一个基本的抽屉应用程序,当我画一条新线时,我必须删除最后一条。这是我的密码:Can';t在JavaSwing中从JPanel中删除JComponents,java,swing,graphics,mouseevent,Java,Swing,Graphics,Mouseevent,我有一个基本的抽屉应用程序,当我画一条新线时,我必须删除最后一条。这是我的密码: 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[] a
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());
}
}
}
这也是我的在线课程:
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(),但没有成功。如果在移除组件后添加
panel.repaint()
,它将正常工作。然而,我强烈建议MyLine不应该扩展JComponent。覆盖用于绘制的面板中的paintComponent(Graphics g)
方法(在本例中为panel
),并在该方法内绘制线。这样您就不必删除组件,我认为这是更好、更安全的方法。同意@LuxxMiner,MyLine
不应该是JComponent
。它应该只提供一个draw(Graphics)
方法,可以由渲染它的任何组件调用。在调用repaint
之前,您需要revalidate
以强制布局管理器更新UIThanx,但是如果现在我调整框架的大小,组件将消失。为什么?