當前我可以通過按下「添加」JButton將一些定製組件對象添加到JPanel。我還得到了一個「刪除」JButton,我希望與「add」做相反的操作。java刪除組件
我的意圖是,我可以用鼠標選擇一個組件,然後單擊刪除按鈕,然後pressto!,組件就消失了。
我將一個MouseListener掛鉤到面板,並使用MouseEvent,e.getComponent()獲取鼠標點擊的當前組件。因此,如果它返回一個自定義組件,那麼變量「private myComponent current」(已設置爲null)將指向該組件。然後我可以點擊「刪除」按鈕將其刪除。一個actionListener已經添加在「刪除」按鈕中,並在主體中調用this.remove(current)(如果current不爲null)。
但是,這不起作用,因爲我不能刪除組件!任何指針?
如果有一種優雅的方式來管理添加/刪除組件,請建議!
public class MainDisplayPanel extends JPanel implements ActionListener, MouseListener{
private JButton newClassButton;
private JButton deleteButton;
private Resizable current;
private Resizable resizer;
public MainDisplayPanel(LayoutManager layout) {
super(layout);
newClassButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addResizer();
}
});
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
this.addMouseListener(this);
this.add(newClassButton);
this.add(deleteButton);
}
public void addResizer() {
//JPanel panel = new JPanel();
//panel.setBackground(Color.white);
resizer = new Resizable(new ClassBox());
this.add(resizer);
this.revalidate();
this.repaint();
}
public void actionPerformed(ActionEvent e) {
if(current!=null)
{
this.remove(current);
this.revalidate();
this.repaint();
}
}
public void mouseClicked(MouseEvent e) {
System.out.println(e);
Component component = e.getComponent();
if(component instanceof Resizable)
current= (Resizable) e.getComponent();
}
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.add(new MainDisplayPanel(null));
jframe.setSize(new Dimension(600,400));
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} Doh!
現在,在addResizer()方法中。每次按下添加按鈕添加一個新的可調整大小的對象時,之前添加的對象發生了什麼?我敢肯定,他們成爲null因爲resizer變量不再引用它們?即使情況如此,他們仍然顯示在面板上...如果我按刪除,只有新添加的Resizable對象被刪除。那麼我在這裏的正確軌道?
編輯:總結我的問題,我迷上了MouseListener錯誤的對象。它應該是可調整大小的對象而不是面板。因此,可變電流始終爲空。
一點很難說沒有一些代碼的確切的問題,但我的猜測是某種範圍界定問題(特別是與任何匿名聽衆)的。否則,我認爲這大致是我想要的...... –
是的,我使用匿名聽衆。也添加了一些代碼。 – bili