javacodex.com
Java Examples
Java Examples
memu home questions

JComponent

With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit from JComponent. However, JFrame and JDialog don't because they implement top-level containers.

The JComponent class extends the Container class, which itself extends Component. The Component class includes everything from providing layout hints to supporting painting and events. The Container class has support for adding components to the container and laying them out. This section's API tables summarize the most often used methods of Component and Container, as well as of JComponent.

Source: (JComponentExample.java)

import java.awt.*;
import javax.swing.*;
 
public class JComponentExample {
 
  public static void main(String[] arguments) {
 
    MyJComponent com = new MyJComponent();
 
    // create a basic JFrame
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JComponent Example");
    frame.setSize(300,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // add the JComponent to main frame
    frame.add(com);
 
    frame.setVisible(true);
 
  }
}
 
class MyJComponent extends JComponent {
  public void paint(Graphics g) {
    g.setColor(Color.red);
    g.fillOval(50, 10, 150, 150);
  }
}
 

Output:

$ java JComponentExample
Output



Contact: javacodex@yahoo.com