【问题标题】:Java ActionListener action not performed未执行 Java ActionListener 操作
【发布时间】:2014-07-07 10:05:09
【问题描述】:

我有一个 JButton,它应该从我的 GUI 中的 JTable 中删除选定的行。但是,由于某种原因,我用来执行此操作的 ActionListener() 中的代码似乎从未被调用...

private void addListeners(){
    ...
    //removeBtn = new JButton("Remove");
    removeBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println("Remove button clicked. Printed from actionListener. ");
            removeRow(e);
        }
    });

removeRow() 方法稍后在同一个类中定义:

public void removeRow(ActionEvent arg0){
    System.out.println("'Remove' button pressed, Printed from 'removeRow()' method. ");
    int selectedRow = jEntityFilterTable.getSelectedRow();
    DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
    model.removeRow(selectedRow);
    System.out.println("Selected row should have been removed. Printed from 'removeRow()' method. ");

removeBtn 在类的顶部使用以下行声明为全局变量:

private JButton removeBtn = new JButton("Remove");

当我运行代码并单击 GUI 上的“删除”按钮时,什么也没有发生,我什至看不到控制台中显示的调试...但我不知道为什么 - 任何人都可以发现我做错了什么?为什么没有调用 actionListener/removeRow() 方法?

编辑 07/07/2014 @ 13:20

根据要求,这里是课程相关部分的完整代码:

public class JConfigurationPane extends JPanel implements UndoableEditListener, ChangeListener, ActionListener
{
    ...
    private JButton addBtn = null;
    private JButton saveBtn = null;
    private JButton removeBtn = new JButton("Remove"); //null;
    private JButton editBtn = null;
    public boolean addBtnClicked = false;
    public boolean saveBtnClicked = false;
    public boolean removeBtnClicked = false;
    public boolean editBtnClicked = false;
    /**
     * This method initializes 
     * 
     */
    public JConfigurationPane(ConfigurationDataModel dataModel)
    {
    super();

    this.dataModel = dataModel;

    initialize();
    initialiseData();
    addListeners();
}

public JConfigurationPane()
{
    super();

    initialize();

    addListeners();
}

private void addListeners()
{
    System.out.println("--- 'addListeners()' method has been called. ---");
    jcbRxFilterExcludes.addChangeListener(this);

    docRxAddress = jfRxAddress.getDocument();
    docRxPort = jfRxPort.getDocument();
    docRxExerciseID = jfRxExerciseID.getDocument();
    docRxMaxPduSize = jfRxMaxPduSize.getDocument();

    docRxAddress.addUndoableEditListener(this);
    docRxPort.addUndoableEditListener(this);
    docRxExerciseID.addUndoableEditListener(this);
    docRxMaxPduSize.addUndoableEditListener(this);

    addBtn.addActionListener(this);
    /*Add action listeners for other buttons (07/07/2014 @ 08:35) 
    saveBtn.addActionListener(this);
    removeBtn.addActionListener(this);
    editBtn.addActionListener(this);

    Causes an "Exception in thread 'main', java.lang.nullPointerException on: 
        'saveBtn.addActionListener(this);
        'addListeners();' call in 'public JConfigurationPane()'
        'JConfigurationPane panel = new JConfigurationPane()' call in 'main(String[] args)'
    */
    //removeBtn = new JButton("Remove");
    removeBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println("Remove button clicked. Printed from actionListener. ");
            removeRow(e);
        /*  System.out.println("'Remove' button pressed. ");
            int selectedRow = jEntityFilterTable.getSelectedRow();
            DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
            model.removeRow(selectedRow);
            System.out.println("Selected row should have been removed. "); */
        }
    });
}

private void initialiseData()
{
    ...
}

/**
 * This method initializes this
 * 
 */
private void initialize() {
    ...

    /*Create filter buttons */
    System.out.println("------------------JButtons BEING CREATED---------------------");
    addBtn = new JButton("Add");
    addBtn.setBounds(950, 135, 125, 25);
   //     addBtn.addActionListener(new ActionListener(){
//      public void actionPerformed(ActionEvent e){

//      }
//  });
    JButton saveBtn = new JButton("Save");
    saveBtn.setBounds(1100, 135, 125, 25);
    JButton removeBtn = new JButton("Remove");
    removeBtn.setBounds(950, 200, 125, 25);
    JButton editBtn = new JButton("Edit");
    editBtn.setBounds(1100, 200, 125, 25);
    System.out.println("------------------JButtons CREATED-------------------------");

    ...

    /*Add filter buttons */
    System.out.println("-------------------JButtons BEING ADDED TO GUI--------------------");
    this.add(addBtn);
    this.add(saveBtn);
    this.add(removeBtn);
    this.add(editBtn);
    System.out.println("------------------JButtons ADDED TO GUI---------------------");
}

/**
 * This method initializes jfRxAddress  
 *  
 * @return javax.swing.JTextField   
 */
private JTextField getJfRxAddress()
{
    ...
}

/**
 * This method initializes jfRxPort 
 *  
 * @return javax.swing.JTextField   
 */
private JTextField getJfRxPort()
{
    ...
}

/**
 * This method initializes jfRxExerciseID   
 *  
 * @return javax.swing.JTextField   
 */
private JTextField getJfRxExerciseID()
{
    ...
}

/**
 * This method initializes jEntityFilterPane    
 *  
 * @return javax.swing.JScrollPane  
 */
private JScrollPane getJEntityFilterPane()
{
    ...
}

/**
 * This method initializes jEntityFilterTable   
 *  
 * @return javax.swing.JTable   
 */
private JTable getJEntityFilterTable()
{
    ...
}

/**
 * This method initializes jEntitySymbolsPane   
 *  
 * @return javax.swing.JScrollPane  
 */
private JScrollPane getJEntitySymbolsPane()
{
    ...
}

/**
 * This method initializes jEntitySymbolsTable  
 *  
 * @return javax.swing.JTable   
 */
private JTable getJEntitySymbolsTable()
{
    ...
}

/*Method to add buttons to 'Plugin Configuration' window */
private void addButtons(){
    /*Buttons moved up to initialize() method on 25/06/2014 @ 17:00 */
    JButton addBtn = new JButton("Add");
    JButton saveBtn = new JButton("Save");
    JButton removeBtn = new JButton("Remove");
    JButton editBtn = new JButton("Edit");

    addBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            /*(25/06/2014 @ 15:20) Need to add code here to add a new editable row to 'Entity Filter' table */
            addBtnClicked = true;
        }
    });
    //addBtn.setBounds(1150, 135, 30, 15);
    saveBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            /*(25/06/2014 @ 15:20) Need to add code here to save the data in the 'Entity Filter' table to a set of variables */
            saveBtnClicked = true;
        }
    });
    //saveBtn.setBounds(1190, 135, 30, 15);
    removeBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        /*(25/05/2014 @ 15:25) Need to add code here to remove the data in selected row from variables, and remove row from table */
            removeBtnClicked = true;
        }
    });
    //removeBtn.setBounds(1150, 160, 30, 15);
    editBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            /*(25/06/2014 @ 15:25) Need to add code here to enable editing of data in selected row */
            editBtnClicked = true;
        }
    });
    //editBtn.setBounds(1190, 160, 30, 15);
    System.out.println("'addButtons()' method is being called by 'initialize()' in JConfigurationPanel.java");
}

/**
 * This method initializes jcbRxFilterExcludes  
 *  
 * @return javax.swing.JCheckBox    
 */
private JCheckBox getJcbRxFilterExcludes()
{
    ...
}

/**
 * This method initializes jfRxMaxPduSize   
 *  
 * @return javax.swing.JTextField   
 */
private JTextField getJfRxMaxPduSize()
{
    ...
}

@Override
public void undoableEditHappened(UndoableEditEvent editEvent)
{
    ...
}

@Override
public void stateChanged(ChangeEvent changeEvent)
{
    ...
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setMinimumSize(new Dimension(500,500));
    frame.setSize(new Dimension(500,500));

    JConfigurationPane panel = new JConfigurationPane();

    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent arg0) {
    /*Check which button has been pressed, perform a different action depending on which button it was. Reset the check variables
     * to false after performing action */

    // TODO Auto-generated method stub
    /*Code to add row to table when button is pressed */
    System.out.println("'Add' button pressed.");

    DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();

    Object[] obj = new Object[]{}; 

    System.out.println("Row Count: " + model.getRowCount());
    System.out.println("1st Column: " + model.getColumnName(0));
    System.out.println("Column Count: " + model.getColumnCount());

    model.addRow(obj);

    System.out.println("--- ActionListener added to 'addBtn' ---");

    /*Code to remove selected row from the table when button is clicked 
    int selectedRow = jEntityFilterTable.getSelectedRow();
    model.removeRow(selectedRow); */

}

public void removeRow(ActionEvent arg0){
    System.out.println("'Remove' button pressed. Printed from 'removeRow()' method. ");
    int selectedRow = jEntityFilterTable.getSelectedRow();
    DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
    model.removeRow(selectedRow);
    System.out.println("Selected row should have been removed. Printed from 'removeRow()' method. ");
}
}

【问题讨论】:

  • 没有足够的代码。您应该提供 stackoverflow.com/help/mcve 。但我敢打赌,使用removeBtn = new JButton("Remove");,您正在创建一个与您在屏幕上看到的按钮不同的 new 按钮(可能是在其他地方创建的......)
  • 确保您没有错误地将 JButton 替换到某处,因此您最终会得到一个没有附加 ActionListener 的按钮。
  • 我之前用private JButton removeBtn = null;removeBtn 声明为全局变量。但是,鉴于您的评论,我尝试将全局声明更改为 private JButton removeBtn = new JButton("Remove");,然后从 addListeners() 方法中的代码中删除行 removeBtn = new JButton("Remove");,但是当我单击“删除”时,我仍然遇到同样的问题,没有任何反应' GUI 上的按钮...
  • 愚蠢的问题:你真的在代码中的某处调用addListeners()吗?
  • 是的,我在构造函数中调用addListeners()

标签: java swing jtable actionlistener defaulttablemodel


【解决方案1】:

在您的initialize() 方法中,您添加到面板的removeBtn 是该方法的局部变量。 addButtons() 方法中也会发生同样的事情。然后,稍后,当您调用addListeners() 时,您会将ActionListener 添加到未添加到面板的私有成员JButton。从initialize() 方法中删除本地JButton removeBtn 并初始化成员一。

【讨论】:

  • 您好,感谢您的回答和指出这些问题。我已经按照您的建议做了 - 摆脱了我创建的所有“新”私有 JButton,并改用了成员 JButton。但是,当我现在运行我的代码时,一旦所有初始化代码都运行了(并且我在控制台中收到“...正在创建...”消息和“addListeners() 方法已被调用”消息),我然后再次获得带有空指针异常的“线程主异常”。这次它发生在stateChanged() 方法中的dataModel.setEntityFilterExcludes(jcbRxFilterExcludes.isSelected());
  • 嗯,很好,你原来的问题已经解决了,但是如果你正在寻找关于你的新问题的建议,你需要发布 stateChanged() 方法的内容。
【解决方案2】:

尝试将按钮声明为最终字段。如果你的代码的某些部分改变了你的按钮对象,你会得到一个警告。

【讨论】:

  • 我知道你还不能发表评论,但这真的应该是一个评论......不过是个好主意。
  • 我试了一下,但它对我运行代码时发生的事情没有任何影响......
【解决方案3】:

再次出现空指针异常。

在您使用的代码中:

JConfigurationPane panel = new JConfigurationPane();

代替:

public JConfigurationPane(ConfigurationDataModel dataModel)

为什么你有两个构造函数?你为什么要把数据模型传给班级?

另外,不要使用 setBounds() 来设置按钮的大小/位置。 Swing 旨在与布局管理器一起使用,因此请使用布局管理器。也许您会从使用FlowLayout 的面板开始。

最后,下面的代码(可能)不起作用:

model.removeRow(selectedRow);

选中的行是指表视图中的行,而不是表模型中的行。如果您的代码进行排序或过滤,那么索引可能会有所不同。您首先需要使用以下方法转换所选索引:

JTable.convertRowIndexToModel(...);

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多