Hi All
i have java question for you guys.
How can i add columns by click the button. i want my program keep adding columns whenever user click the button. any help.
Thank you

I'm assuming you're talking about adding columns to a JTable? Check out the methods in the DefaultTableModel class.

I'm also assuming you're talking about adding columns to a JTable.

Adding a new column to a table is quite simple. it goes something like this:

JTable tabell = new JTable();
TableColumn column = new TableColumn();
column.setHeaderValue("New column");

Unfortunately, the hard part is getting meaningful data to the column.

A JTable (usually) works in the following way:
You have a list of data.
You have a TableModel that transform an object from the list of data into columns.
You have the JTable that converts the information from the TableModel into TableColumns.

This way each column is mapped to specific data from the objects in your datalist. By dynamically adding columns in the way I described above, you also have to either write a tablemodel that handles variable number of columns, or you somehow have to fetch the data you want to display in a custom cellRenderer.

To answer the rest of the question - how to add it with a button:

class ButtonListener implements ActionListener {

    private JTable table;

    public ButtonListener(JTable table) {
        this.table = table;

    public void actionPerformed(ActionEvent e) {
        TableColumn column = new TableColumn();
        column.setHeaderValue("column header");


JTable table = new JTable();
JButton button = new JButton();
button.addActionListener(new ButtonListener());

Hope that helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.