Java - How To Remove All JTable Data In Button Click Using Java NetBeans
Project Source Code:
package javaapp;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Woirk extends JFrame {
public Woirk(){
this.setTitle("Remove JTable Contents");
this.setSize(450, 350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
JButton btn1 = new JButton("Delete Data");
JButton btn2 = new JButton("Add Data");
JScrollPane pane = new JScrollPane();
Object[] columns = {"ID","First Name","Last Name","Age"};
Object[][] rows = {{"1","AAAA","BBBB","11"},{"2","AAAA","BBBB","22"},
{"3","AAAA","BBBB","33"},{"4","AAAA","BBBB","44"},
{"5","AAAA","BBBB","55"},{"6","AAAA","BBBB","66"},
{"7","AAAA","BBBB","11"},{"8","AAAA","BBBB","11"},
{"9","AAAA","BBBB","11"},{"10","AAAA","BBBB","11"},
{"11","AAAA","BBBB","11"},{"12","AAAA","BBBB","11"},
{"13","AAAA","BBBB","11"},{"14","AAAA","BBBB","11"},
{"15","AAAA","BBBB","11"},{"16","AAAA","BBBB","11"}
};
DefaultTableModel model = new DefaultTableModel();
model.setDataVector(rows, columns);
JTable table = new JTable();
table.setModel(model);
pane.setViewportView(table);
GroupLayout gl = new GroupLayout(panel);
panel.setLayout(gl);
gl.setHorizontalGroup(gl.createParallelGroup()
.addGroup(gl.createSequentialGroup()
.addContainerGap()
.addComponent(btn1)
.addGap(10)
.addComponent(btn2)
)
.addGroup(gl.createSequentialGroup()
.addContainerGap()
.addComponent(pane, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)
)
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addContainerGap()
.addGroup(gl.createParallelGroup()
.addComponent(btn1)
.addComponent(btn2)
)
.addGap(10)
.addGroup(gl.createParallelGroup()
.addComponent(pane, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE)
)
);
add(panel);
/*
set a new DefaultTableModel with null data to the JTable
with this the the data will despair data from the JTable
*/
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
table.setModel(new DefaultTableModel(null, columns));
}
});
/*
now reset a the first model with his data to the JTable
with this the data will be shown data in the JTable
*/
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
table.setModel(model);
}
});
}
public static void main(String[] args){
Woirk w = new Woirk();
w.setVisible(true);
}
}
Download Projects Source Code
1 comments:
commentsthank you so much
Reply