首页 文章

如何使用另一个类的actionPerformed方法删除一个类/组件中的按钮?

提问于
浏览
0

在我正在设计的代码中,我在我的应用程序的主JFrame中实例化了一个JButton,它使用ActionListener在另一个类/组件中引用actionPerformed方法 . 我想知道是否有办法在运行所述actionPerformed方法(点击它)时删除该按钮 . 换句话说,actionPerformed方法是否可以引用回激活它的按钮?

1 回答

  • 0

    你能获得引起ActionListener激活的对象的引用吗?是通过ActionEvent参数的 getSource() 方法 .

    即,

    public void actionPerformed(ActionEvent evt) {
       Object theSource = evt.getSource();
    }
    

    但是有一个警告:如果您在多个设置中使用此ActionListener或Action,例如菜单,则源可能根本不是按钮 .

    至于使用它来“删除”按钮,您将需要获取组件的容器,如:

    public void actionPerformed(ActionEvent evt) {
       JButton button = (JButton) evt.getSource(); // danger when casting!
       Container parent = button.getParent();
       parent.remove(button);
       parent.revalidate();
       parent.repaint();
    }
    

    但是,我必须警告说,如果事件不是由JButton引起的,或者如果父级使用的布局管理器没有被移除,那么你将遇到麻烦 . 我不得不怀疑在这里使用CardLayout会更好 .


    例如 . ,

    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    
    public class RemoveButton extends JPanel {
       private static final long serialVersionUID = 1L;
       private static final int BUTTON_COUNT = 5;
       private Action removeMeAction = new RemoveMeAction("Remove Me");
       public RemoveButton() {
          for (int i = 0; i < BUTTON_COUNT; i++) {
             add(new JButton(removeMeAction));
          }
       }
    
       private static void createAndShowGui() {
          RemoveButton mainPanel = new RemoveButton();
    
          JFrame frame = new JFrame("Remove Buttons");
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    class RemoveMeAction extends AbstractAction {
       private static final long serialVersionUID = 1L;
    
       public RemoveMeAction(String name) {
          super(name); // to set button's text and actionCommand
       }
    
       @Override
       public void actionPerformed(ActionEvent evt) {
          Object source = evt.getSource();
    
          // AbstractButton is the parent class of JButton and others
          if (source instanceof AbstractButton) {
             AbstractButton button = (AbstractButton) source;
             Container parent = button.getParent();
    
             parent.remove(button);
             parent.revalidate();
             parent.repaint();
          }
       }
    }
    

相关问题