JLabel label = new JLabel("Hello World"); JComponent component = new JComponent() { protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(label.getText(), 10, 20); } }; component.add(label);
JComponent customComponent = new JComponent() { public void paintComponent(Graphics g) { super.paintComponent(g); // Custom painting code } };This example shows how to create a custom JComponent by extending the JComponent class and overriding the paintComponent() method. In both examples, the JComponent is part of the javax.swing package library.