13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

354Chapter 16Getting in the Swing of Things: Designing a GUI for BudgetProIt c<strong>on</strong>sists of three parts, <strong>on</strong>e for the account name, <strong>on</strong>e for the total valueof the account, and <strong>on</strong>e for the remaining value. Each part will be representedby its own label, using a JLabel object. (We could have d<strong>on</strong>e the entire linein <strong>on</strong>e label, but this gives us a few more objects to manipulate.) Since we wantto group the labels together, we create a JPanel, which is a Swing c<strong>on</strong>tainer,to hold all these objects. We’ll also add the JButt<strong>on</strong> object (the variable namedupt<strong>on</strong>).A JLabel is a simple Swing object. You can c<strong>on</strong>struct an empty <strong>on</strong>e withnew JLabel(); but you can also c<strong>on</strong>struct a label with a String as its initialvalue, which is more useful. You can later change a label’s value with a call toits setText() method, as you see here from line 117:117 tot.setText("Total: $"+current.getTotal());16.7.2.2 FlowLayoutThe JLabels are added to their JPanel, but with no positi<strong>on</strong> argument, unlikethe JFrame and BorderLayout used in main(). JPanel has a different defaultlayout manager: It uses FlowLayout. With it, added objects are placed side byside according to the window size. If the window is narrowed, they will simplyflow <strong>on</strong>to the next line. (You w<strong>on</strong>’t see this behavior if you narrow the Budget-Pro window, but that’s because the JPanel has been added to the JFrame’sNORTH regi<strong>on</strong>, which means it’s no l<strong>on</strong>ger just a FlowLayout that determinessizes.) FlowLayout is a layout that’s easy to use, but doesn’t give you muchc<strong>on</strong>trol; it was just fine for our purposes here.16.7.2.3 BoxLayoutAnother simple layout mechanism is the BoxLayout. It allows you to place theobjects like stacking boxes—though they can be stacked horiz<strong>on</strong>tally as well asvertically. Look at line 224:224 retval.setLayout(new BoxLayout(retval, BoxLayout.X_AXIS));Here we are creating a BoxLayout object and associating it with ourJFrame to manage its objects. When we create a BoxLayout we can tell it thatwe want to stack our objects horiz<strong>on</strong>tally (using either X_AXIS or LINE_AXIS)or vertically (using either Y_AXIS or PAGE_AXIS). Note that the BoxLayout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!