Barry A. Burd

Articles From Barry A. Burd

page 1
page 2
page 3
page 4
page 5
page 6
page 7
page 8
73 results
73 results
How to Install JavaFX and Scene Builder

Article / Updated 10-13-2017

Before you can jump into Java GUIs, you need to install JavaFX and Scene Builder. GUI programs have two interesting characteristics: GUI programs typically contain lots of code. Much of this code differs little from one GUI program to another. GUI programs involve visual elements. The best way to describe visual elements is to “draw” them. Describing them with code can be slow and unintuitive. To make your GUI life easier, you can use JavaFX and Scene Builder. With Scene Builder, you describe your program visually. Scene Builder automatically turns your visual description into Java source code and XML code. Installing Scene Builder Installing Scene Builder is like installing most software. Here's how you do it: Visit Scene Builder. Click the Download button. When you do, a list of download options appears. Click the button corresponding to your computer's operating system (Windows, Mac, or Linux). As a result, the download begins. On a Windows computer, you get an .exe file. Double-click the file to begin the installation. On a Mac, you get a .dmg file. Depending on your Mac web browser's setting, the browser may or may not expand the .dmg file automatically. If not, double-click the .dmg file to begin the installation. Follow the installation routine's instructions. On a Windows computer, you accept a bunch of defaults. On a Mac, you drag the Scene Builder's icon to the Applications folder. That's it! You've installed Scene Builder. Installing e(fx)clipse Eclipse has its own, elaborate facility for incorporating new functionality. An Eclipse tool is called an Eclipse plug-in. When you first install Eclipse, you get many plug-ins by default. Then, to enhance Eclipse's power, you can install many additional plug-ins. Eclipse's e(fx)clipse plug-in facilitates the creation of JavaFX applications. You can add the plug-in to your existing installation of Eclipse, but it's much simpler to download a new copy of Eclipse (a copy with e(fx)clipse already installed). Here's how you get the new copy of Eclipse: Visit e(fx)clipse. Look for the page containing All-in-One downloads. On the All-in One downloads page, look for a way to download a copy of Eclipse for your operating system. Your Eclipse download's word length (32-bit or 64-bit) must match your Java version's word length. Follow the appropriate links or click the appropriate buttons to begin the download. Install this new copy of Eclipse on your computer. Place the new copy of Eclipse in a brand-new folder. That way, you don't have to uninstall your old copy of Eclipse. (In fact, it's helpful to have two separate Eclipse installations on your computer.) When you launch your new copy of Eclipse, the program prompts you for a place on your hard drive for your workspace (the place on your hard drive where this session's Eclipse projects live). At this point, you have a choice: You can have two different folders for two different workspaces — one workspace for your original copy of Eclipse and a second workspace for your new copy of Eclipse. Doing so keeps your original work separate from other work. Also, with two different workspaces, you can run both copies of Eclipse simultaneously. Alternatively, you can point both versions of Eclipse to the same folder (and thus, to the same workspace). Doing so keeps all your work in one place. You don't have to change workspaces. On the minus side, you can't run two copies of Eclipse using the same workspace simultaneously. Don't fret over the decision you make about Eclipse workspaces. In any copy of Eclipse, you can switch from one workspace to another. You can decide on a particular workspace whenever you launch Eclipse. You can also move from one workspace to another by selecting File → Switch Workspace on Eclipse's main menu.

View Article
A Few Things about Java GUIs

Article / Updated 10-13-2017

Before you jump into Java GUIs, there are a few things you should know. Java comes with three sets of classes for creating GUI applications: The Abstract Window Toolkit (AWT): The original set of classes, dating back to JDK 1.0. Classes in this set belong to packages whose names begin with java.awt. Components in this set have names like Button, TextField, Frame, and so on. Each component in an AWT program has a peer — a companion component that belongs to the computer's own operating system. For example, when you create an AWT Button, a Mac computer creates its own kind of button to be displayed on the user's screen. When the same program runs on a Windows computer, the Windows computer creates a different kind of button (a Windows button) to display on the computer's screen. The Java code in the AWT interacts with the Mac or Windows button, adding additional functionality where functionality is needed. The AWT implements only the kinds of components that were available on all common operating systems in the mid-1990s. So, using AWT, you can add a button to your application, but you can't easily add a table or a tree. Java Swing: A set of classes created to fix some of the difficulties posed by the use of the AWT. Swing was introduced in J2SE 1.2. Classes in this set belong to packages whose names begin with javax.swing. Components in this set have names like JButton, JTextField, JFrame, and so on. Unlike an old AWT component, a Swing component has no peer. When you create a JButton in your Java program, the computer's operating system doesn't create a button of its own. Instead, the JButton that you see is a pure Java object. Java's visual rendering code draws this object on a window. This is both good news and bad news. The good news is, a Swing program looks the same on every operating system. In a Swing program, you can create table components and tree components because Java simply draws them in the computer's window. The bad news is, Swing components aren't pretty. A JButton looks primitive and crude compared to a Mac button or a Windows button. Java's Swing classes replace some (but not all) of the classes in the older AWT. To use some of the Swing classes, you have to call on some of the old AWT classes. JavaFX: The newest set of GUI classes in Oracle standard Java. JavaFX comes with new(er) versions of Java 7 and with all later versions of Java. Classes in this set belong to packages whose names begin with javafx. JavaFX supports over 60 kinds of components. (Sure, you want a Button component. But do you also want an Accordion component? JavaFX has one.) In addition, JavaFX supports multitouch operations and takes advantage of each processor's specialized graphics capabilities.

View Article
Getting a Value from a Method in Java

Article / Updated 10-13-2017

Say that you’re sending a friend to buy groceries. You make requests for groceries in the form of method calls. You issue calls such as goToTheSupermarketAndBuySome(bread); goToTheSupermarketAndBuySome(bananas); The things in parentheses are parameters. Each time you call your goToTheSupermarketAndBuySome method, you put a different value in the method’s parameter list. Now what happens when your friend returns from the supermarket? “Here’s the bread you asked me to buy,” says your friend. As a result of carrying out your wishes, your friend returns something to you. You made a method call, and the method returns information (or better yet, the method returns some food). The thing returned to you is called the method’s return value, and the type of thing returned to you is called the method’s return type. A Java example To see how return values and a return types work in a real Java program, check out the code below. This code shows a method that returns a value importjava.text.NumberFormat; import static java.lang.System.out; classGoodAccount { String lastName; int id; double balance; <strong> </strong> <strong>double getInterest(double rate) {</strong> <strong>double interest;</strong> out.print("Adding "); out.print(rate); out.println(" percent…"); <strong>interest = balance * (rate / 100.0);</strong> <strong>return interest;</strong> <strong>}</strong> void display() { NumberFormat currency = NumberFormat.getCurrencyInstance(); out.print("The account with last name "); out.print(lastName); out.print(" and ID number "); out.print(id); out.print(" has balance "); out.println(currency.format(balance)); } } This code calls the method in the code above. importjava.util.Random; importjava.text.NumberFormat; classProcessGoodAccounts { public static void main(String args[]) { Random myRandom = new Random(); NumberFormat currency = NumberFormat.getCurrencyInstance(); <strong>GoodAccount</strong>anAccount; doubleinterestRate; <strong>doubleyearlyInterest;</strong> for (int i = 0; i < 3; i++) { anAccount = new GoodAccount(); anAccount.lastName = "" + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a'); anAccount.id = myRandom.nextInt(10000); anAccount.balance = myRandom.nextInt(10000); anAccount.display(); <strong> </strong> <strong>interestRate = myRandom.nextInt(5);</strong> <strong>yearlyInterest = anAccount.getInterest(interestRate);</strong> System.out.print("This year's interest is "); System.out.println(currency.format(yearlyInterest)); System.out.println(); } } } Here’s a run from the code. How return types and return values work Here’s what happens when getInterest is called: The value of balance is 9508.00, and the value of rate is 2.0. So the value of balance * (rate / 100.0) is 190.16 — one hundred ninety dollars and sixteen cents. The value 190.16 gets assigned to the interest variable, so the statement return interest; has the same effect as return 190.16; The return statement sends this value 190.16 back to the code that called the method. At that point in the process, the entire method call in the first set of code — anAccount.getInterest(interestRate) — takes on the value 190.16. Finally, the value 190.16 gets assigned to the variable yearlyInterest. If a method returns anything, a call to the method is an expression with a value. That value can be printed, assigned to a variable, added to something else, or whatever. Anything you can do with any other kind of value, you can do with a method call. Working with the method header When you create a method or a method call, you have to be careful to use Java’s types consistently. Make sure that you check for the following: In the first set of code, the getInterest method’s header starts with the word double. When the method is executed, it should send a double value back to the place that called it. Again in the first set of code, the last statement in the getInterest method is return interest. The method returns whatever value is stored in the interest variable, and the interest variable has type double. So far, so good. In the second set of code, the value returned by the call to getInterest is assigned to a variable named yearlyInterest. Sure enough, yearlyInterest is of type double. That settles it! The use of types in the handling of method getInterest is consistent in both sets of code. I’m thrilled!

View Article
Let the Objects Do the Work in Java

Article / Updated 10-13-2017

When I was a young object, I wasn’t as smart as the objects you have nowadays. Consider, for example, the object in the code below This object not only displays itself, but it can also fill itself with values. importjava.util.Random; importjava.text.NumberFormat; import static java.lang.System.out; classBetterAccount { String lastName; int id; double balance; <strong> </strong> <strong>void fillWithData() {</strong> <strong>Random myRandom = new Random();</strong> <strong>lastName = "" +</strong> <strong> </strong> <strong>(char) (myRandom.nextInt(26) + 'A') +</strong> <strong> </strong> <strong>(char) (myRandom.nextInt(26) + 'a') +</strong> <strong> </strong> <strong>(char) (myRandom.nextInt(26) + 'a');</strong> <strong> </strong> <strong>id = myRandom.nextInt(10000);</strong> <strong>balance = myRandom.nextInt(10000);</strong> <strong>}</strong> void display() { NumberFormat currency = NumberFormat.getCurrencyInstance(); out.print("The account with last name "); out.print(lastName); out.print(" and ID number "); out.print(id); out.print(" has balance "); out.println(currency.format(balance)); } } Here’s a way to use the class in the code above. Check out the new code. classProcessBetterAccounts { public static void main(String args[]) { <strong>BetterAccount</strong>anAccount; for (int i = 0; i < 3; i++) { anAccount = new <strong>BetterAccount</strong>(); <strong>anAccount.fillWithData();</strong> anAccount.display(); } } } The second set of code is pretty slick. Because the code in the first listing is so darn smart, the new code has very little work to do. This new code just creates a BetterAccount object and then calls the methods in the first listing of code.

View Article
Reading and Writing Strings in Java

Article / Updated 10-13-2017

A String is a bunch of characters in Java. It’s like having several char values in a row. To read a String value from the keyboard, you can call either next or nextLine: The methodnextreads up to the next blank space. For example, with the input Barry A. Burd, the statements String firstName = keyboard.next(); String middleInit = keyboard.next(); String lastName = keyboard.next(); assign Barry to firstName, A. to middleInit, and Burd to lastName. The methodnextLinereads up to the end of the current line. For example, with input Barry A. Burd, the statement String fullName = keyboard.nextLine(); assigns Barry A. Burd to the variable fullName. To display a String value, you can call one of your old friends, System.out.print or System.out.println. A statement like out.print("Customer's full name: "); displays the String value "Customer's full name: ". You can use print and println to write String values to a disk file. In a Java program, you surround the letters in a String literal with double quote marks. Adding strings to things In Java, you can put a plus sign between a String value and a numeric value. When you do, Java turns everything into one big String value. To see how this works, consider the following code. import java.util.Scanner; import static java.lang.System.out; class ProcessMoreData { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); String fullName; double amount; boolean taxable; double total; out.print("Customer's full name: "); fullName = keyboard.nextLine(); out.print("Amount: "); amount = keyboard.nextDouble(); out.print("Taxable? (true/false) "); taxable = keyboard.nextBoolean(); if (taxble) { total = amount * 1.05; } else { total = amount; } out.println(); out.print("The total for "); out.print(fullName); out.print(" is "); out.print(total); out.println("."); keyboard.close(); } } Replace the last several lines in of the code below with the following single line: out.println("The total for " + fullName + " is " + total + "."); Fun with word order Write a program that inputs six words from the keyboard. The program outputs six sentences, each with the first word in a different position. For example, the output of one run might look like this: only I have eyes for you. I only have eyes for you. I have only eyes for you. I have eyes only for you. I have eyes for only you. I have eyes for you only.

View Article
How to Put String Variables to Good Use in Java

Article / Updated 10-13-2017

The Java program below takes the user’s input and echoes it back on the screen. This is a wonderful program, but (like many college administrators) it doesn’t seem to be particularly useful. Take a look at a more useful application of Java’s String type. import java.util.Scanner; import static java.lang.System.out; class ProcessMoreData { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); <strong>String fullName;</strong> double amount; boolean taxable; double total; out.print("Customer's full name: "); <strong>fullName = keyboard.nextLine();</strong> out.print("Amount: "); amount = keyboard.nextDouble(); out.print("Taxable? (true/false) "); taxable = keyboard.nextBoolean(); if (taxble) { total = amount * 1.05; } else { total = amount; } out.println(); out.print("The total for "); <strong>out.print(fullName);</strong> out.print(" is "); out.print(total); out.println("."); keyboard.close(); } } A run of the code in is shown below. The code stores Barry A. Burd in a variable called fullName and displays the fullName variable’s content as part of the output. To make this program work, you have to store Barry A. Burd somewhere. After all, the program follows a certain outline: <strong><em>Get a name.</em></strong> <em>Get some other stuff.</em> <em>Compute the total.</em> <strong><em>Display the name</em></strong><em> (along with some other stuff).</em> If you don’t have the program store the name somewhere, by the time it’s done getting other stuff and computing the total, it forgets the name (so the program can’t display the name).

View Article
Saving Time and Money with Java Classes

Article / Updated 10-13-2017

When you start learning object-oriented programming, you may think that this class idea is a big hoax. Some geeks in Silicon Valley had nothing better to do, so they went to a bar and made up some confusing gibberish about classes. They don’t know what it means, but they have fun watching people struggle to understand it. Well, that’s not what classes are all about. Classes are serious stuff. What’s more, classes are useful. Many reputable studies have shown that classes and object-oriented programming save time and money. Even so, the notion of a class can be elusive. Even experienced programmers — the ones who are new to object-oriented programming — have trouble understanding how an object differs from a class. Classes, objects, and tables Because classes can be mysterious, I’ll expand your understanding with another analogy. The image below has a table of three purchases. The table’s title consists of one word (the word Purchase), and the table has three column headings: the words unitPrice,quantity, and taxable. Well, this has the same stuff — Purchase, unitPrice, quantity, and taxable. class Purchase { double unitPrice; int quantity; boolean taxable; } So in the image below, think of the top part of the table (the title and column headings) as a class. Like the code above, this top part of the table tells you what it means to be a Purchase. (It means having an unitPrice value, a quantity value, and a taxable value.) A class is like the top part of a table. And what about an object? Well, an object is like a row of a table. For example, with this code, you create two objects (two instances of the Purchase class). class ProcessPurchases { public static void main(String[] args) { <strong>Purchase purchase1 = new Purchase();</strong> purchase1.unitPrice = 20.00; purchase1.quantity = 3; purchase1.taxable = true; <strong>Purchase purchase2 = new Purchase();</strong> purchase2.unitPrice = 20.00; purchase2.quantity = 3; purchase2.taxable = false; double purchase1Total = purchase1.unitPrice * purchase1.quantity; if (purchase1.taxable) { purchase1Total *= 1.05; } double purchase2Total = purchase2.unitPrice * purchase2.quantity; if (purchase2.taxable) { purchase2Total *= 1.05; } if (purchase1Total == purchase2Total) { System.out.println("No difference"); } else { System.out.println("These purchases have different totals."); } } } The first object has unitPrice value 20.00, quantity value 3, and taxable value true. In the corresponding table, the first row has these three values — 20.00, 3, and true. Some questions and answers Here’s the world’s briefest object-oriented programming FAQ: Can I have an object without having a class? No, you can’t. In Java, every object is an instance of a class. Can I have a class without having an object? Yes, you can. In fact, many Java programs create a class without an object. That’s just fine. It’s business as usual. After I’ve created a class and its instances, can I add more instances to the class? Yes, you can. In a for loop, you could create a dozen instances and you’d have a dozen rows in the table. With no objects, three objects, four objects, or more objects, you still have the same old class. Can an object come from more than one class? Bite your tongue! Maybe other object-oriented languages allow this nasty class cross-breeding, but in Java, it’s strictly forbidden. That’s one thing that distinguishes Java from some of the languages that preceded it: Java is cleaner, more uniform, and easier to understand.

View Article
Looping in Style: Enhanced for Loops to Step through Java’s Array Values

Article / Updated 10-13-2017

You can make an enhanced for loop to step through a bunch of values, including an array’s values. Let’s take a look at an enhanced for loop that steps through an array’s values. To see such a loop, start with this code. The loop looks something like this: for (int roomNum = 0; roomNum < 10; roomNum++) { out.println(guestsIn[roomNum]); } To turn this into an enhanced for loop, you make up a new variable name. (What about the name howMany? Nice name.) Whatever name you choose, the new variable ranges over the values in the guestsIn array. for (int howMany : guestsIn) { out.println(howMany); } This enhanced loop uses this format. for (<em>TypeName variableName</em> : <em>RangeOfValues</em>) { <em>Statements</em> } The RangeOfValues can belong to an enum type. Here, the RangeOfValues belongs to an array. Enhanced for loops are nice and concise. But don’t be too eager to use enhanced loops with arrays. This feature has some nasty limitations. For example, the new howMany loop doesn’t display room numbers. Room numbers are avoided because the room numbers in the guestsIn array are the indices 0 through 9. Unfortunately, an enhanced loop doesn’t provide easy access to an array’s indices. And here’s another unpleasant surprise. Start with the following loop: for (int roomNum = 0; roomNum < 10; roomNum++) { guestsIn[roomNum] = diskScanner.nextInt(); } Turn this traditional for loop into an enhanced for loop, and you get the following misleading code: for (int howMany : guestsIn) { howMany = diskScanner.nextInt(); <strong>//Don't do this</strong> } The new enhanced for loop doesn’t do what you want it to do. This loop reads values from an input file and then dumps these values into the garbage can. In the end, the array’s values remain unchanged. It’s sad but true. To make full use of an array, you have to fall back on Java’s plain old for loop.

View Article
Grabbing Input for Your Java Programs

Article / Updated 10-13-2017

The Java code you see below illustrates some pithy issues surrounding the input of data. For one thing, the program gets input from both the keyboard and a disk file. (The program gets a room number from the keyboard. Then the program gets the number of guests in that room from the occupancy file.) To make this happen, this program sports two Scanner declarations: one to declare keyboard and a second to declare diskScanner. import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; import static java.lang.System.out; public class ShowOneRoomOccupancy { public static void main(String args[]) throws FileNotFoundException { Scanner keyboard = new Scanner(System.in); Scanner diskScanner = new Scanner(new File("occupancy")); int whichRoom; out.print("Which room? "); <strong>whichRoom = keyboard.nextInt();</strong> for (int roomNum = 0; <strong>roomNum < whichRoom</strong>; roomNum++) { diskScanner.nextInt(); } out.print("Room "); out.print(whichRoom); out.print(" has "); out.print(diskScanner.nextInt()); out.println(" guest(s)."); keyboard.close(); diskScanner.close(); } } Later in the program, the call keyboard.nextInt reads from the keyboard, and diskScanner.nextInt reads from the file. Within the program, you can read from the keyboard or the disk as many times as you want. You can even intermingle the calls — reading once from the keyboard, and then three times from the disk, and then twice from the keyboard, and so on. All you have to do is remember to use keyboard whenever you read from the keyboard and use diskScanner whenever you read from the disk. Another interesting tidbit concerns the number of files you keep on your computer. In real life, having several copies of a data file can be dangerous. You can modify one copy and then accidentally read out-of-date data from a different copy. Sure, you should have backup copies, but you should have only one “master” copy — the copy from which all programs get the same input. In a real-life program, you don’t copy the occupancy file from one project to another. What do you do instead? You put an occupancy file in one place on your hard drive and then have each program refer to the file using the names of the file’s directories. For example, if your occupancy file is in the c:\Oct\22 directory, you write Scanner diskScanner = new Scanner(new File("c:\\oct\\22\\occupancy"));

View Article
How to Use Java’s do Statement

Article / Updated 10-13-2017

To write the Java program you see below, you need a loop — a loop that repeatedly asks the user whether the importantData.txt file should be deleted. The loop continues to ask until the user gives a meaningful response. /* * DISCLAIMER: Neither the author nor John Wiley & Sons, * Inc., nor anyone else even remotely connected with the * creation of this book, assumes any responsibility * for any damage of any kind due to the use of this code, * or the use of any work derived from this code, * including any work created partially or in full by * the reader. * * Sign here:_______________________________ */ import java.io.File; import java.util.Scanner; class IHopeYouKnowWhatYoureDoing { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); char reply; <strong> </strong> <strong>do {</strong> <strong> </strong> <strong>System.out.print("Reply with Y or N…");</strong> <strong>System.out.print(" Delete the importantData file? ");</strong> <strong>reply = keyboard.findWithinHorizon(".", 0).charAt(0);</strong> <strong> </strong> <strong>} while (reply != 'Y' && reply != 'N');</strong> if (reply == 'Y') { new File("importantData.txt").delete(); System.out.println("Deleted!"); } else { System.out.println("No harm in asking!"); } keyboard.close(); } } The loop tests its condition at the end of each iteration, after each of the user’s responses. That’s why the program has a do loop (also known as a do … while loop). With a do loop, the program jumps right in, executes some statements, and then checks a condition. If the condition is true, the program goes back to the top of the loop for another go-around. If the condition is false, the computer leaves the loop (and jumps to whatever code comes immediately after the loop). A closer look at the do statement The format of a do loop is do { <em> Statements</em> } while (<em>Condition</em>) Writing the Condition at the end of the loop reminds the programmer that the computer executes the Statements inside the loop first. After the computer executes the Statements, the computer goes on to check the Condition. If the Condition is true, the computer goes back for another iteration of the Statements. With a do loop, the computer always executes the statements inside the loop at least once: <strong>//This code prints something:</strong> int twoPlusTwo = 2 + 2; do { System.out.println("Are you kidding?"); System.out.println("2+2 doesn’t equal 5."); System.out.print ("Everyone knows that"); System.out.println(" 2+2 equals 3."); } while (twoPlusTwo == 5); This code displays Are you kidding? 2+2 doesn't equal 5 …and so on and then tests the condition twoPlusTwo == 5. Because twoPlusTwo == 5 is false, the computer doesn’t go back for another iteration. Instead, the computer jumps to whatever code comes immediately after the loop. Do I hear an echo? In a do statement, repeatedly read numbers from the keyboard. Display each number back to the user on the screen. After displaying a number, ask whether the user wants to continue entering numbers. When the user replies with the letter n, stop. Here's a sample run of the program: Enter a number: 5 5 Continue? (y/n) y Enter a number: 81 81 Continue? (y/n) y Enter a number: 29 29 Continue? (y/n) n Done! Tally ho! In a do statement, repeatedly read int values from the keyboard and keep track of the running total. The user says, “I want to stop entering values” by typing one final int value — the value 0. At that point, the program displays the total of all values that the user entered.

View Article
page 1
page 2
page 3
page 4
page 5
page 6
page 7
page 8