create account

How to Create a Simple Java GUI with GNU Compiler for Java (GCC): Using Swing and AWT in a Graphical User Interface by cheretta

View this thread on: hive.blogpeakd.comecency.com
· @cheretta · (edited)
$18.96
How to Create a Simple Java GUI with GNU Compiler for Java (GCC): Using Swing and AWT in a Graphical User Interface
Most users are used to seeing an application interface with buttons an boxes. The Java programmer can provide this by using the Swing and AWT packages.

There are two quotes by Albert Einstein that every Java programmer should keep close to their hearts:

>Why should I memorize something when I know where to find it?
>Know where to find the information and how to use it - that's the secret of success.

And that, of course, is the secret to writing good Java applications. It's not done by creating completely new functionality, but by using the packages and classes that are already in existence. A good example of this is building Java GUIs (Graphical User Interfaces).

If a programmer is designing an application to be used in a Windows type environment then the user will not expect to have an application that works only on the command line. They will expect to see an application that:

- has its own window
- has elements such as text boxes and buttons
- will respond to their actions (such as clicking the mouse buttons)

It is, therefore, just a matter of learning which packages to access and how to use them.

### Java GUI Packages

Java has two packages that are used in the creation of a GUI:

1. **AWT** - the Abstract Windowing Toolkit - provides the functionality for the GUI
2. **Swing**- provides the components (the widgets) for the GUI

![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129137/aje2gj6jiqgndxd4b01t.png)


They are imported in the same way that any other Java package is imported:
```
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
```
With the packages (and the classes that they contain) loaded the widgets (or components) for the GUI can be defined:

```
public class simpleForm extends JFrame {
private JPanel contentPanel;
private JLabel jLabel1;
private JLabel jLabel2;
private JTextField jTextField1;
private JButton jButton1;
```

![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129192/xxddxdeajbqwmwuidrad.png)

Here there are four key components to the GUI:

**JFrame** - the window for the GUI
**JPanel** - a container in the GUI window for the widgets
**JLabel**- a label widget
**JTextField** - a text field widget
**JButton** - a button widget

The widgets can now be added to the container in the Java frame.

### Adding Swing Widgets to a Container

Widgets are all added to the container in the same way and it is, therefore, a good ideas to have a separate method to do this:
```
private void addElement (Container c, Component w, int x, int y, int h, int w) {
w.setBounds(x, y, h, w);
c.add(e);
}
```
![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129233/yxfl3mqxncaxwsfwih1e.png)


The code uses the setBounds method to define where the widget is placed within the container (with x=0, y=0 being the top left hand corner) and it defines the height and width of the widget. Adding widgets is now a very easy task:
```
simpleForm() {
contentPanel = (JPanel)getContentPane();
contentPanel.setLayout(null); // a blank form
jLabel1 = new JLabel("Action:");
addElement(contentPanel, jLabel1,0,0,100,20);
jTextField1 = new JTextField();
addElement(contentPanel, jTextField1,0,20,100,20);
jButton1 = new JButton("Click Me");
addElement(contentPanel, jButton1,0,100,100,20);
```
![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129272/djcnadeey5ejg7g5cfwv.png)

With the widgets in place the next step is to introduce some functionality into the GUI.

### Adding Functionality to a Java Swing Widget
Functionality is added to widgets by making use of an ActionListener. In this example clicking the button will update the contents of a text box.:
```
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextField1.setText("Button clicked");
}
});
```
![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129308/xqu9vkjdclrlorjktn2z.png)

It is a very simple example, but does show just how easy it is to make a GUI fully functional.

### Displaying the GUI
The penultimate step is to define how the screen is to be displayed:
```
setTitle("A Simple Form");
setSize(200, 200); // The GUI dimensions
setLocation(new Point(150, 150)); //The GUI position
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
```
![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129353/fthqbbx379ex6xlc65mi.png)

And finally the GUI is called from the main method:
```
public static void main(String args[]) {
new simpleForm();
}
}
```
![image.png](https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129390/agm5vin2lwaqrvtpzpnx.png)

The code can now be saved as simpleForm.java, compiled and the run to show a very simple example of a GUI. Summary There are 5 steps to creating a Java based GUI:

Step 1. import the GUI packages
Step 2. declare the widgets to be used in the GUI
Step 3. add the widgets to a container
Step 4. implement any event handling
Step 5. show the GUI

And that's all there is to it - a simple but effective way of providing an interface for an application user.

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@cheretta/how-to-create-a-simple-java-gui-with-gnu-compiler-for-java-using-swing-and-awt-in-a-graphical-user-interface">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , ,
properties (23)
authorcheretta
permlinkhow-to-create-a-simple-java-gui-with-gnu-compiler-for-java-using-swing-and-awt-in-a-graphical-user-interface
categoryutopian-io
json_metadata{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":22711503,"name":"gcc","full_name":"gcc-mirror/gcc","html_url":"https://github.com/gcc-mirror/gcc","fork":false,"owner":{"login":"gcc-mirror"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","java","tutorial","howto","free"],"users":["cheretta"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129137/aje2gj6jiqgndxd4b01t.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129192/xxddxdeajbqwmwuidrad.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129233/yxfl3mqxncaxwsfwih1e.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129272/djcnadeey5ejg7g5cfwv.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129308/xqu9vkjdclrlorjktn2z.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129353/fthqbbx379ex6xlc65mi.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129390/agm5vin2lwaqrvtpzpnx.png"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129137/aje2gj6jiqgndxd4b01t.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129192/xxddxdeajbqwmwuidrad.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129233/yxfl3mqxncaxwsfwih1e.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129272/djcnadeey5ejg7g5cfwv.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129308/xqu9vkjdclrlorjktn2z.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129353/fthqbbx379ex6xlc65mi.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1515129390/agm5vin2lwaqrvtpzpnx.png"],"moderator":{"account":"shreyasgune","reviewed":true,"pending":false,"flagged":false}}
created2018-01-05 05:18:42
last_update2018-01-05 14:00:09
depth0
children3
last_payout2018-01-12 05:18:42
cashout_time1969-12-31 23:59:59
total_payout_value13.161 HBD
curator_payout_value5.798 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length5,370
author_reputation5,144,315,983,714
root_title"How to Create a Simple Java GUI with GNU Compiler for Java (GCC): Using Swing and AWT in a Graphical User Interface"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id27,198,812
net_rshares2,367,867,037,607
author_curate_reward""
vote details (13)
@ecoman1 ·
i would like to learn ...
properties (22)
authorecoman1
permlinkre-cheretta-how-to-create-a-simple-java-gui-with-gnu-compiler-for-java-using-swing-and-awt-in-a-graphical-user-interface-20180105t143455167z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-05 14:35:00
last_update2018-01-05 14:35:00
depth1
children0
last_payout2018-01-12 14:35:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length25
author_reputation3,594,222,183
root_title"How to Create a Simple Java GUI with GNU Compiler for Java (GCC): Using Swing and AWT in a Graphical User Interface"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id27,296,776
net_rshares0
@shreyasgune ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/UCvqCsx).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorshreyasgune
permlinkre-cheretta-how-to-create-a-simple-java-gui-with-gnu-compiler-for-java-using-swing-and-awt-in-a-graphical-user-interface-20180105t125859497z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-05 12:59:09
last_update2018-01-05 12:59:09
depth1
children0
last_payout2018-01-12 12:59:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation4,924,803,411,962
root_title"How to Create a Simple Java GUI with GNU Compiler for Java (GCC): Using Swing and AWT in a Graphical User Interface"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id27,276,883
net_rshares0
@utopian-io ·
### Hey @cheretta I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-cheretta-how-to-create-a-simple-java-gui-with-gnu-compiler-for-java-using-swing-and-awt-in-a-graphical-user-interface-20180105t204139423z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-01-05 20:41:39
last_update2018-01-05 20:41:39
depth1
children0
last_payout2018-01-12 20:41:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,506
author_reputation152,955,367,999,756
root_title"How to Create a Simple Java GUI with GNU Compiler for Java (GCC): Using Swing and AWT in a Graphical User Interface"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id27,366,312
net_rshares0