import javax.swing.*; import java.awt.*; public class Example1 extends JFrame { public Example1() { String[] columnNames = {"Name", "Age", "Gender"}; Object[][] rowData = {{"Alice", 25, "Female"}, {"Bob", 32, "Male"}, {"Charlie", 48, "Male"}}; JTable table = new JTable(rowData, columnNames); add(new JScrollPane(table)); setTitle("Example 1"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new Example1(); } }
import javax.swing.*; import java.awt.event.*; public class Example2 extends JFrame { private JTable table; public Example2() { String[] columnNames = {"Name", "Age", "Gender"}; Object[][] rowData = {{"Alice", 25, "Female"}, {"Bob", 32, "Male"}, {"Charlie", 48, "Male"}}; table = new JTable(rowData, columnNames); add(new JScrollPane(table)); JButton hideButton = new JButton("Hide"); hideButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { table.setVisible(false); } }); add(hideButton, BorderLayout.NORTH); JButton showButton = new JButton("Show"); showButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { table.setVisible(true); } }); add(showButton, BorderLayout.SOUTH); setTitle("Example 2"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new Example2(); } }This example creates a JFrame with a JTable and two buttons: one to hide the table and one to show it again. The ActionListener for each button simply calls the setVisible() method of the JTable with the appropriate value. This demonstrates how you can dynamically hide and show a JTable based on user interactions.