import javax.swing.*; import java.awt.*; public class ExampleComponent extends JComponent { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillRect(10, 10, 50, 50); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.add(new ExampleComponent()); frame.setSize(200, 200); frame.setVisible(true); } }
import javax.swing.*; import java.awt.event.*; public class ButtonExample extends JFrame implements ActionListener { public void actionPerformed(ActionEvent e) { repaint(); } public ButtonExample() { JButton button = new JButton("Click Me"); button.addActionListener(this); add(button); setSize(200, 200); setVisible(true); } public static void main(String[] args) { new ButtonExample(); } }In this example, we create a button that when clicked triggers the repaint() method. This causes the component to be redrawn on the GUI. We also implement the ActionListener interface which includes the actionPerformed() method that is called when the button is clicked. We then add the button to a JFrame and display it. Package library: javax.swing.