2012-08-23 77 views
1

您好我有一个像JButton定义:的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要导出的用户点击后按钮,但没有任何反应,没有异常。我做错了吗?

+0

请参阅[*如何使用操作*](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html)。 – trashgod

回答

3

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

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

是的你是对的。我只是添加了其他按钮之前和我想知道为什么这不应该以同样的方式工作。无论如何,我会用你的方法去。 – ErrorNotFoundException

2
  1. 您发布的代码甚至不会编译
  2. 您应该ActionListener添加到您的JButton如@丹在他的回答已经表明
  3. 你应该确保你关闭FileWriterfinally区块中。现在,如果发生异常,它将不会被关闭
  4. 如果您在事件调度线程上导出表,则最终将出现无响应的用户界面。考虑使用SwingWorker。请参阅Concurrency in Swing教程以获取更多信息
  5. 避免使用setLayout(null)setBounds。使用体面的LayoutManager而不是
相关问题