Welcome!

Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

Related Topics: Java IoT

Java IoT: Article

Lesson 12: An Introduction to Graphical User Interfaces with Swing - Part I

Everything is a little better, faster, and more convenient in Swing

Java comes with the whole bunch of classes that you'll be using to create graphical applications. There are two main groups of classes (libraries) that are used for creating windows in Java: AWT and Swing.

AWT and Swing
When Java was originally created, only AWT library was available for working with graphics. This library is a simple set of classes like Button, TextField, Label and others. Pretty soon, another and more advanced library called Swing was introduced. It also includes buttons, text fields, and other window controls. The names of the Swing components start with the letter J, for example JButton, JTextField, JLabel, and so on.

Everything is a little better, faster, and more convenient in Swing, but you can use it only if you're sure that your programs will run on the computers with JVMs that support Swing classes. In this lesson we'll create a simple calculator program using Swing.

Note. There is yet another set of Java classes which is a part of Eclipse platform called Standard Widget Toolkit (SWT), but since it's not a part of Java SDK, we won't discuss it here.

Packages and Import Statements
Java comes with many classes that are organized in packages. Some packages include classes responsible for drawing, while other packages have classes to work with the Internet, and so on. For example the class String is located in the package called java.lang, and the full name of the class String is java.lang.String.

Java compiler knows where to find classes that are located in java.lang, but there are many other packages with useful classes, and it's your responsibility to let the compiler know where the classes from your program live. For example, most of the Swing classes live in one of the following two packages:

javax.swing
javax.swing.event

It would be annoying to write a full class name every time you use it, and to avoid this you can write import statements just once above the class declaration line, for example:

import javax.swing.JFrame;
import javax.swing.JButton;

class Calculator{
   JButton myButton = new JButton();
   JFrame myFrame = new JFrame();
}

These import statements will allow you to use the short class names like JFrame or JButton, and Java compiler will know where to look for these classes.

If your need to use several classes from the same package, you do not have to list each of them in the import statement, just use the wild card. In the following example the star (asterisk) makes all classes from the package javax.swing visible to your program:

import javax.swing.*;

Still, it's better to use separate import statements, so you can see what exactly the class is importing from each package. You can find more about packages in the lesson on packages and imports (http://java.sys-con.com/read/49108.htm).

Major Swing Elements
These are some of the major objects that Swing applications consist of:

  • A window or a frame that can be created using the class JFrame.
  • An invisible panel or a pane that holds all these buttons, text fields, labels, and other components. Panels are created by the class JPanel.
  • Window controls like buttons (JButton), text fields (JTextfield), lists (JList), and so on.
  • Layout managers that help arrange all these buttons and fields on a panel.
Usually a program creates an instance of a JPanel and assigns the layout manager to it. Then, it can create some window controls and add them to the panel. After that, add the panel to the frame, set the frame's size and make it visible.

But displaying a frame is only half of the job, because the window controls should know how to respond to various events, for example a click on the button.

In this Lesson we'll learn how to display nice-looking windows, and the next lesson  is about writing code that will respond to events that may happen with elements of this window.

Our next goal is to create a simple calculator that knows how to add two numbers and display the result. Create a new project in Eclipse named My Calculator and add a new class SimpleCalculator with the following code:


import javax.swing.*;
import java.awt.FlowLayout;

public class SimpleCalculator {
public static void main(String[] args) {
// Create a panel
JPanel windowContent= new JPanel();

// Set a layout manager for this panel
FlowLayout fl = new FlowLayout();
windowContent.setLayout(fl);
// Create controls in memory
JLabel label1 = new JLabel("Number 1:");
JTextField field1 = new JTextField(10);
JLabel label2 = new JLabel("Number 2:");
JTextField field2 = new JTextField(10);
JLabel label3 = new JLabel("Sum:");
JTextField result = new JTextField(10);
JButton go = new JButton("Add");

// Add controls to the panel
windowContent.add(label1);
windowContent.add(field1);
windowContent.add(label2);
windowContent.add(field2);
windowContent.add(label3);
windowContent.add(result);
windowContent.add(go);

// Create the frame and add the panel to it
JFrame frame = new JFrame("My First Calculator");

frame.setContentPane(windowContent);

// set the size and make the window visible
frame.setSize(400,100);
frame.setVisible(true);
}
}
Compile and run this program and it'll display a window that looks like this one:


More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that Akvelon will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Akvelon is a business and technology consulting firm that specializes in applying cutting-edge technology to problems in fields as diverse as mobile technology, sports technology, finance, and healthcare.
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
SYS-CON Events announced today that WineSOFT will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...