How can I create a titled border around some components with a specific color?

Scott Stanchfield

When creating a titled border, you can pass another Border on which the title will be drawn.

For example

Border red = BorderFactory.createLineBorder(Color.red);
p.setBorder(BorderFactory.createTitledBorder(red, "Age group"));

Looking at this in context of a sample application:
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;

import javax.swing.JRadioButton;
import javax.swing.border.Border;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;

public class Sample2 {

  public static void main(String[] args) {
    new Sample2().go();
  }

  public void go() {
    JFrame f = new JFrame("Sample");
    JPanel p = new JPanel(new GridLayout(0,1,3,3));
    Border red = BorderFactory.createLineBorder(Color.red);
    p.setBorder(BorderFactory.createTitledBorder(red, "Age group"));
    JRadioButton b1 = new JRadioButton("< 6");
    JRadioButton b2 = new JRadioButton("7-13");
    JRadioButton b3 = new JRadioButton("14-20");
    JRadioButton b4 = new JRadioButton("21-35");
    JRadioButton b5 = new JRadioButton("36-62");
    JRadioButton b6 = new JRadioButton("> 62");

    p.add(b1);
    p.add(b2);
    p.add(b3);
    p.add(b4);
    p.add(b5);
    p.add(b6);
    
    ButtonGroup group = new ButtonGroup();
    group.add(b1);
    group.add(b2);
    group.add(b3);
    group.add(b4);
    group.add(b5);
    group.add(b6);
    
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(p);
    f.pack();
    f.setVisible(true);
  }
}
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact