NickPick said:
With NetBeans I created a file with it's JPanel function (new file -->
JPanel Form) and saved the file after adding a button. How can I now
call this class so that the window gets visible? When I create a
second file main.java and instanciate the JPanel object in the
public static void main(String[] args) {
NewPanel n=new NewPanel();
}
the JPanel window does not open. What do I need to change?
many thanks
ok, fine, I can do it all with a JFrame. But my problem is that I
don't manage to instantiate the frame object when I call it from a
different class.
NewJFrame n=new NewJFrame();
does not open a new window, when I call it from public static void
main(String[] args) from the main class.
How can I make it visible?
If you want to use JFrames and other Swing components with out NetBeans
GUI creator, then there's a tutorial for that too.
<
http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html>
But in fairness, I don't actually see the answer to your question there,
which is kinda dumb on Sun's part.
Once you get a top level window (JDialog, JFrame, JWindow, etc.) set up
and ready to go, you should call it's pack() method to signal to the
layout manager that it needs to get the window contents ready to
display, then call setVisible(true) to hand off control of the window to
the Event Dispatch Thread.
Because of that last part, it's required to do this all on the EDT
itself, or you risk calamity.
Besides those two methods, you should also set a window close policy
(EXIT or DISPOSE work best) and I like to center up the window in the
middle of the screen too (setLocation... for that).
class NewJFrame extends JFrame {
public static void main( String... args ) {
javax.swing.SwingUtilities.invokeLater( new Runnable() {
public void run() {
createAndShowGui();
}
} );
}
private static void createAndShowGui() {
NewJFrame f = new NewJFrame();
f.pack();
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setLocationRelativeTo( null ); // null = center on screen
f.setVisible( true );
}
}
The order is not terribly important, although you do need to call pack()
before setVisible(). Realistic, I think the call to pack(),
setDefaultCloseOperation and setLocalion... ought to go inside the
constructor for the NewJFrame, but for this short example I didn't need
a constructor, so I just put them outside of it.
Note that when you create a JFrame in NetBeans, something very like this
is auto-generated for you (check the source code view in the GUI editor).