Swing Components

Here are some basic ones. Refer to the online help to learn about more.

Labels:

Text

Check Boxes

  • The appearance of a checkbox is platform dependent, but usually shows a square followed by some text.

  • The user clicks on the square to select or unselect the option and can check or uncheck as many boxes as they wish.

  • Use the JCheckbox class to create a checkbox.

  • Here are a few useful methods that belong to the JCheckbox class:

    JCheckbox(String text) - create a checkbox with the passed-in text as the label.

    JCheckbox(String text, boolean on) - create a checkbox with the passed-in text as the label. If on is true, the the checkbox is selected. If on is false, the checkbox is not selected. (Note this is 1.1 only.)

    String getLabel() - returns a string containing the checkbox's label.

    boolean getState() - returns true if the check box is selected, false if it is not.

Radio Buttons

  • A radio button is a group of options that can be checked, but only 1 item can be selected at a time.

  • The appearance of a radio button is dependent on the look and feel, but usually shows a circle followed by some text.

  • The user clicks on the circle to select or unselect the option and when one option is selected, the currently selected option becomes unselected.

  • Radio buttons are created by creating JRadioButton objects and grouping them together with a ButtonGroup.

  • First create the ButtonGroup and JRadioButton objects:
    ButtonGroup    fruitRadioButtons = new ButtonGroup();
    
    JRadioButton applebox = new JRadioButton("apples", true);
    JRadioButton orangebox = new JRadioButton("orange", true);
    
  • Then add the radio buttons to the button group and add the radio buttons to the layout:
    fruitRadioButtons.add(applebox);
    fruitRadioButtons.add(orangebox);
    getContentPane().add(applebox);
    getContentPane().add(orangebox);
    

Buttons

  • Use the JButton class to create button.

  • Here are a few useful methods that belong to the JButton class:

    JButton() - create an empty button.

    JButton(String text) - create a button labeled with the specified text.

    String getLabel() - returns the label for the button.

    setLabel(String text) - set the label of the button to the passed-in text.

  • Don't forget to add the button to the layout.