O'Reilly logo

Head First Java, 2nd Edition by Bert Bates, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. Using Swing: Work on Your Swing

image with no caption

Swing is easy. Unless you actually care where things end up on the screen. Swing code looks easy, but then you compile it, run it, look at it and think, “hey, that’s not supposed to go there.” The thing that makes it easy to code is the thing that makes it hard to control—the Layout Manager. Layout Manager objects control the size and location of the widgets in a Java GUI. They do a ton of work on your behalf, but you won’t always like the results. You want two buttons to be the same size, but they aren’t. You want the text field to be three inches long, but it’s nine. Or one. And under the label instead of next to it. But with a little work, you can get layout managers to submit to your will. In this chapter, we’ll work on our Swing and in addition to layout managers, we’ll learn more about widgets. We’ll make them, display them (where we choose), and use them in a program. It’s not looking too good for Suzy.

Swing components

Component is the more correct term for what we’ve been calling a widget. The things you put in a GUI. The things a user sees and interacts with. Text fields, buttons, scrollable lists, radio buttons, etc. are all components. In fact, they all extend javax.swing.JComponent.

Note

A widget is technically a Swing Component. Almost every thing you can stick in a GUI extends from javax.swing.JComponent.

Components can be nested ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required