Subclass JPanel : JPanel « Swing « Java Tutorial






Subclass JPanel
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class OvalPanel extends JPanel {
  Color color;
  public OvalPanel() {
    this(Color.black);
  }
  public OvalPanel(Color color) {
    this.color = color;
  }
  public void paintComponent(Graphics g) {
    int width = getWidth();
    int height = getHeight();
    g.setColor(color);
    g.drawOval(0, 0, width, height);
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("Oval Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(2, 2));
    Color colors[] = { Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW };
    for (int i = 0; i < 4; i++) {
      OvalPanel panel = new OvalPanel(colors[i]);
      panel.add(new JButton("asdf"));
      frame.add(panel);
    }
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}








14.45.JPanel
14.45.1.Using JPanel as a containerUsing JPanel as a container
14.45.2.Using JPanel as a canvasUsing JPanel as a canvas
14.45.3.Subclass JPanelSubclass JPanel
14.45.4.Customizing JPanel Look and Feel
14.45.5.A basic panel that displays a small up or down arrow.
14.45.6.A panel that allows the user to select a date.
14.45.7.A JPanel with a textured background.
14.45.8.Gradient Panel