Stanley Mungai
Stanley Mungai

Reputation: 4150

JButton Not performing Any Action

Hi I have a JButton defined like:

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);
    }
}

Am trying to get the JTable to be exported after the user clicks the button but nothing happens and no exception is raised. Am I doing it the wrong way?

Upvotes: 1

Views: 180

Answers (2)

Robin
Robin

Reputation: 36611

  1. The code you post will not even compile
  2. You should add the ActionListener to your JButton as @Dan already showed in his answer
  3. You should make sure you close the FileWriter in a finally block. Now, when an exception occurs it will not be closed
  4. You will end up with a non-responsive UI if you export the table on the Event Dispatch Thread. Consider using a SwingWorker. Consult the Concurrency in Swing tutorial for more information
  5. Avoid the use of setLayout( null ) and setBounds. Use a decent LayoutManager instead

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

You are not adding the ActionListener to your button correctly. The correct way is:

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

Upvotes: 3

Related Questions