Single-purpose calculators are frequently used as exercises for Java beginners. The instructor tasks the students with writing a command line program that calculates the area of a room in square feet, or it calculates body mass index (BMI), or it converts an amount of money in one currency to another, etc.

To do the same thing with a graphical user interface (GUI), such as with Java Swing, would be too difficult for a Java beginner, because there is a lot more overhead. Or is it? After all, the three major integrated development environments (IDEs) include GUI form designers.

In this tutorial, I will walk you through the process of making a simple tip calculator with Java Swing.

We could prototype this in HTML with CSS and JavaScript (which, as you might know, is not the scripting edition of Java). A tip calculator for a Web browser is actually a trivially simple project.

To use Java Swing for this tip calculator project might seem like overkill. But for anything slightly more involved, JavaScript’s sloppy type system can be a hindrance rather than a help.

There are a few concepts in common between the Java and JavaScript versions of this project. If nothing else, the concept of event listeners is a concept in common. There’s also some kind of document object model in both.

An event listener watches out for a specific kind of event and creates an event object whenever that event occurs. We’re not talking about a big event, like a wedding or a concert, but a small event that occurs in your computer or similar device.

For example, if you move your mouse even just a little bit, that’s an event. If you scroll down a little bit on this page, that’s also an event (an event that I hope occurs again and again, but gradually, until you have read this whole article).

The big difference between the Java and the JavaScript versions of this project is that in Java both the event listeners and the event objects are well defined according to clearly documented types.

I’m going to use Apache NetBeans for my Java IDE. Both Eclipse and IntelliJ IDEA have form designers. They look different from the NetBeans form designer, but they accomplish the same goal of giving you a WYSIWYG experience for designing forms. Connecting the generated forms to your “handwritten code” follows the same principles of Java.

#java #gui #tip-calculator #java-swing

Easy Java Swing exercise: Tip calculator
1.10 GEEK