How to add new JTable with rows and columns by clicking button?

976 views Asked by At

I am a beginner in Java and I need help.

I want to add table with rows and columns in JFrame or JPanel when a button is clicked. How to add new table with rows and columns by clicking button?

1

There are 1 answers

1
Programmer On
  1. First you have to add JButton to frame
  2. Than add ActionListener in button
  3. than make a list when button is pressed like this

    JButton b = new JButton("Click Me");
    b.addActionListener(new ActionListener() {
    
    public void actionPerformed(ActionEvent e) {
    
    String[] columnNames = {"First Name",
                "Last Name",
                "Sport",
                "# of Years",
                "Vegetarian"};
    
    Object[][] data = {
                {"Kathy", "Smith",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"John", "Doe",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Sue", "Black",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Jane", "White",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Joe", "Brown",
                 "Pool", new Integer(10), new Boolean(false)}
            };
    
        JTable table = new JTable(data, columnNames);
        add(table);
    
    }
    });
    

More information on JButton & JTable.