import java.awt.*; import javax.swing.*; public class MyPanel extends JPanel { public MyPanel() { JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); JButton button3 = new JButton("Button 3"); add(button1); add(button2); add(button3); } public void clearAllButtons() { removeAll(); // repaint(); } public static void main(String[] args) { JFrame frame = new JFrame("My Panel Example"); MyPanel panel = new MyPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); panel.clearAllButtons(); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextFieldsPanel extends JPanel { private JTextField firstName = new JTextField(10); private JTextField lastName = new JTextField(10); private JButton submitButton = new JButton("Submit"); private JButton clearButton = new JButton("Clear"); public TextFieldsPanel() { add(firstName); add(lastName); add(submitButton); add(clearButton); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearAllFields(); } }); } public void clearAllFields() { firstName.setText(""); lastName.setText(""); } public static void main(String[] args) { JFrame frame = new JFrame("Text Fields Example"); TextFieldsPanel panel = new TextFieldsPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }This code creates a JPanel with two text fields and two buttons, and a method clearAllFields() that clears the text in both text fields when called. The ActionListener of the clearButton uses removeAll() method to remove all the components from the panel. The Java package library used in the examples is java.awt.