Java JButton Click event and JTable: Click on the JButton and the JTable will show or appear

Here I am sharing you a simple but useful way about JButton and JTable. Sometimes in designing   software, where we are using JButton and JTable, we may need to code or design in such a way that just user will click on the JButton (by using JButton ActionListener) and the JTable will show or appear with its value. Copy the code below and run on your computer.

Here is the code:

 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

class ClickandTable extends JFrame

{

private JPanel topPanel;

private JTable table;

public JScrollPane scrollPane;

public JScrollPane scrollPane1;

private String[] columnNames=new String[3];

private String[][] dataValues=new String[3][3];

JButton button=new JButton(“Click Here”);

public ClickandTable()

{

setTitle(“Button Click and JTable Appears”);

setSize(320,300);

setDefaultCloseOperation (EXIT_ON_CLOSE);

button.setBounds(75,200,90,30);

columnNames=new String[] {“Column 1″ ,”Column 2”, “Column 3”};

dataValues=new String[][]

                   {

                   {“a”,”2″,”3″},

                   {“b”,”5″,”6″},

                   {“c”,”8″,”9″}

                   };

topPanel=new JPanel();

topPanel.setLayout(null);

getContentPane().add(topPanel);

table=new JTable();

scrollPane=new JScrollPane(table);

scrollPane.setSize(300,200);

scrollPane1=new JScrollPane(button);

scrollPane1.setSize(90,30);

scrollPane1.setBounds(75,200,150,30);

topPanel.add(scrollPane);       

topPanel.add(scrollPane1);

button.addActionListener(

                                    new ActionListener()

             {

                                    public void actionPerformed(ActionEvent event)

                                     {

                                    TableModel  model=new myTableModel();

            table.setModel(model);

                                      }

                                      }

                                      );

}

public class myTableModel extends DefaultTableModel

{

myTableModel()

{

super(dataValues,columnNames);

}

public boolean isCellEditable(int row,int cols)

{

return true;

}

}

public static void main(String args[])

  {

  ClickandTable x=new ClickandTable();

  x.setVisible(true);

  }  

}JButton click and JTable appear

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: