swing Using Swing for Graphical User Interfaces Adding Components


Example

A component is some sort of user interface element, such as a button or a text field.

Creating a Component

Creating components is near identical to creating a window. Instead of creating a JFrame however, you create that component. For example, to create a JButton, you do the following.

JButton button = new JButton();

Many components can have parameters passed to them when created. For example, a button can be given some text to display.

JButton button = new JButton("Super Amazing Button!");

If you don't want to create a button, a list of common components can be found in another example on this page.

The parameters that can be passed to them vary from component to component. A good way of checking what they can accept is by looking at the paramters within your IDE (If you use one). The default shortcuts are listed below.

  • IntelliJ IDEA - Windows / Linux: CTRL + P
  • IntelliJ IDEA - OS X / macOS: CMD + P
  • Eclipse: CTRL + SHIFT + Space
  • NetBeans: CTRL + P

Example of viewing method parameter information in IntelliJ IDEA

Showing the Component

After a component has been created, you would typically set its parameters. After than, you need to put it somewhere, such as on your JFrame, or on your content pane if you created one.

frame.add(button); //Add to your JFrame
//OR
pane.add(button); //Add to your content pane
//OR
myComponent.add(button); //Add to whatever

Example

Here's an example of creating a window, setting a content pane, and adding a button to it.

JFrame frame = new JFrame("Super Awesome Window Title!"); //Create the JFrame and give it a title
frame.setSize(512, 256); //512 x 256px size
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Quit the application when the JFrame is closed

JPanel pane = new JPanel(); //Create the content pane
frame.setContentPane(pane); //Set the content pane

JButton button = new JButton("Super Amazing Button!"); //Create the button
pane.add(button); //Add the button to the content pane

frame.setVisible(true); //Show the window

Example output