分类: Java
2009-03-15 12:35:49
Remember to import these three packages when working with Swing:
javax.swing.*
java.awt.*
java.awt.event.*
A JFrame object is the physical window that you'll be working with in the Swing API. Making a window appear on the screen is easy enough. Here's the code: JFrame frame = new JFrame("Title Bar Text");
frame.setSize(256,256);
frame.pack();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.show();
I think that code is relatively simple, all it does is create a new JFrame with a size of 256x256, tell Java to exit when the JFrame is closed and shows the window.
You probably want to get started putting components on your brand-new form. Maybe you've even figured out how to and you've discovered that is not what you bargained for. Well, what you don't know is that you need to add a JPanel
to the JFrame's
contentpane before adding components to the JPanel
. Here's what the code looks like:
JFrame frame = new JFrame("Title Bar Text");
JPanel panel = new JPanel();
frame.setSize(256,256);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.show();
Now we are getting somewhere... You probably have already ran this code, so you've discovered that it doesn't look any different than the last example, and that's because JPanels
are just containers for components, the different types of panes are added to the JFrame
's contentpane and then components are added to the JPanel
. Other than Layout objects which I tell you about later, that's all there is for your basic JPanel
.