java - JButton 不执行任何操作

标签 java swing jtable jbutton actionlistener

您好,我有一个 JButton 定义如下:

private JButton btnExp;

private JPanel jpShow = new JPanel();
jpShow.setLayout(null);

btnExp = new JButton("Export");
btnExp.setBounds(100, 250, 120, 25);

jpShow.add(jspTable);
jpShow.add(btnExp);
//Adding Panel to Window.
getContentPane().add(jpShow);

public void actionPerformed(ActionEvent ae) {
    try{
        Object obj = ae.getSource();
        if (obj == btnExp) {
            FileWriter excel = new FileWriter("File.TSV");

            for(int i = 0; i < dtmCustomer.getColumnCount(); i++){
                excel.write(dtmCustomer.getColumnName(i) + "\t");
            }
            excel.write("\n");

            for(int i=0; i< dtmCustomer.getRowCount(); i++) {
                for(int j=0; j < dtmCustomer.getColumnCount(); j++) {
                    excel.write(dtmCustomer.getValueAt(i,j).toString()+"\t");
                }
                excel.write("\n");
            }
            excel.close();
            JOptionPane.showMessageDialog(this, "File Written","Success", JOptionPane.PLAIN_MESSAGE);
        }
    }catch(Exception e){
        System.out.println(e);
    }
}

我试图在用户单击按钮后导出 JTable,但没有任何反应,也没有引发异常。我做错了吗?

最佳答案

您没有正确地将 ActionListener 添加到您的按钮。正确的做法是:

btnExp.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // add here the contents in your actionPerformed method
  }
})

关于java - JButton 不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095134/

相关文章:

java - 为什么我的动画会剪切消息框?

Java Swing 工具栏

java - 如何用java制作一个弹出窗口

java - 表格左侧可见的列名而不是顶部

java - JTable 在运行时更新

java - SQL 命令在 servlet 中未正确结束

Java swing 搜索数组列表和表单

java - 字符串数组数据未显示在 TextView 中

Java:在 HashMap 中使用 ArrayList 以 String 作为键

java - 根据 "Fibonacci sequence"寻找答案