< Zurück | Inhalt | Weiter >

16.7.1 Overview

We divide the work between two GUI classes: one for the main window and the other for the dialog that will appear when we want to create a new subac- count. All of the other GUI elements will be either existing Swing classes or their extensions as anonymous inner classes in our code. (More on those later.) So that means that we have four of our own classes that we’re working with: two from the core of our application, Account and User, and two from the GUI side of things, BudgetPro and AcctDialog. This will be reflected in the package structure; we’ll put BudgetPro and AcctDialog into the net.multitool.gui package. This will effect both the location of the source

(to be put into net/multitool/gui) and the package statement on line 1 of


1 package net.multitool.gui; Instance Variables

Take a look at the picture of the BudgetPro GUI. Count the GUI objects that we need: four buttons, three labels, and let’s not forget the (empty at first) table of subaccounts. These are declared in lines 23–31. (Ignore lines 22 and 32 for now, we’ll cover them later. Line 34 declares our dialog—more on that later, too.)

21 // gui components

22 private JFrame frame; // needed by dialogs to root themselves

23 private JLabel nam;

24 private JLabel tot;

25 private JLabel val;

26 private JButton upton = new JButton(

new ImageIcon("net/multitool/gui/back.gif"));

27 private JButton creat = new JButton("new subaccount");

28 private JButton view = new JButton("view subaccount");

29 private JButton clos = new JButton("quit"); 30

31 private JTable list;

32 private AbstractTableModel model; 33

34 private AcctDialog askem; // make once, use often Main

Skip all the way to the last method of the class, line 289 and following. It’s the main() which gets run when we run this class. If we focus on the major piece involved in getting our GUI together, it’s these lines:

JFrame frame = new JFrame("BudgetPro"); frame.getContentPane().add(status, ...); frame.getContentPane().add(list, ...); frame.getContentPane().add(buttons, ...);

We’re leaving out lots of intermediate text to emphasize the “real” work. We create a JFrame, the outermost window object. We add into it all the other

GUI pieces—the status line, the table list of accounts, and the buttons. The JFrame is a bit odd here, in that you have to add objects to its content pane; other container objects you can just add to directly. (We could have done the getContentPane() once, store the result in an intermediate variable, and do the adds to it, but the efficiency gain is unimportant here because we only need to do this once, to get the GUI started.)

When we’ve got it built, we pack the frame, and make it visible:

frame.pack(); frame.setVisible(true);

That’s the basic core of what you need to do with any GUI: construct its pieces, add them to the frame, pack the frame, and make it visible. Now you’re off and running. The rest is just details.