您好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 :(得分:3)
您没有正确地将ActionListener添加到按钮中。正确的方法是:
btnExp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// add here the contents in your actionPerformed method
}
})
答案 1 :(得分:2)
ActionListener
添加到JButton
,因为@Dan已在答案中显示FileWriter
区块中的finally
。现在,当发生异常时,它将不会被关闭SwingWorker
。有关更多信息,请参阅Concurrency in Swing教程setLayout( null )
和setBounds
。使用合适的LayoutManager
代替