Skip to content

Advanced GUI

trekitch edited this page Apr 23, 2017 · 12 revisions

As you can see from the GUI section, GUI in Java can offer a lot of benefits. Using more advanced GUI concepts you can do things like add menus, change button layout and change color of content.

Swing Components

In Java when you use GUI elements you are using what is called the Swing component. This is why when you use GUI in a class you must import the javax.swing.* class. Swing components are usually put into a container. A container is a component that holds other components. A container is often in the form of a window that you can resize, and move. There is also a thing called a frame. A frame is a window that has a title bar and border. A frame is also the most common component you will use.

Using JFrame

A JFrame is how most components in Java are displayed. The JFrame class has four constructors that you can set when creating the JFrame.

Constructor Use
JFrame() constructs a new frame
JFrame(String title) creates new frame with specified title
JFrame(GraphicsConfiguration gc creates JFrame in the specified configuration
JFrame(String title, GraphicsConfiguration gc creates JFrame in the specified configuration and title

You can create JFrame just like you do other objects in Java.

JFrame newFrame = new JFrame("This is a title");

Now that you have the JFrame object you can use different methods to set the title of the frame, the size of the frame and many more attributes.

JFrame newFrame = new JFrame("This is a title");
newFrame.setSize(200 , 100); //sets he size of the frame to 200 pixels x 100 pixels
newFrame.setVisible(true); //sets the frame to be visible 

Output

Put screenshot here

Using JLabel

A JLabel is an uneditable component that is used to provide information to the user. Just like with the JFrame the JLabel component has a lot of constructors available.

Constructor Use
JLabel() creates label with no image and empty string for title
JLabel(Icon Image) create label with image
JLabel(Icon Image, int horizontalAlignment) creates label with image and specified horizontal alignment
JLabel(String text) create label with specified text
JLabel(String text, Icon Image, int horizontalAlignment) creates label with text and alignment and image
JLabel(String text, int horizontalAlignment creates label with text and alignment

You can create a label to display text and then combine it with the JFrame to display the label.

JLabel greeting = new JLabel("Hello there");

JFrame newFram = new JFrame("Test Frame");
newFrame.setSize(200 , 100); //sets he size of the frame to 200 pixels x 100 pixels
newFrame.setVisible(true); //sets the frame to be visible 
newFrame.add(greeting);

Output

add screenshot here

Clone this wiki locally