Hi, I am trying a method of creating a Java program by putting components on a JFrame instead of on a JPanel and putting the JPanel on the JFrame. I found the following code, which adds a JButton to a JFrame and displays it, in an old Java book:
This code works fine but the button expands to fill the window even when I give it a size altough the book's picture of the program shows the button at proper size.
What is going on? How can I fix this?
What was the book? Did you copy the code exactly? Did the book recommend that way of writing an ActionListener? That is not a good way to write listeners at all. They should have their own classes.
What layout did you expect to apply to the frame? I think it is a layout problem, and the layout overrides the suggested size of the button.
I shall move this discussion to our GUIs forum.
Joined: Nov 30, 2012
Hi, thanks for responding.
It's a very old book. I am aware that this is not the best way to do a GUI - I normally put a JPanel in a JFrame; I simply wonder why it worked in the book and not for me.
I changed the book's code as follows:
different variable names;
The book's button's action was to close the program; my program displays a message.
I created a new project and copied the code in the book exactly and it still didn't work.
I understand your comments about layouts and while that might make the program work, it doesn't explain why the book's method, with no layout, doesn't work for me. I'm wondering if Java or JFrame has changed so that this won't work now.
If anyone has an answer or wants to play around and find the answer, great, I'd love to know what you find but it's not important enough to really matter.
also, layoutManagers work with setPreferredSize(...), they do not work with setSize()
the frame is OK with setSize, as no layoutManager is required to display the frame on the screen
Joined: Oct 13, 2005
It can’t be that old a book if it knows about add replacing getContentPane().add.
Wwhich book was it?
And which layout are you using? Hint: you are using a layout, but might not know which. It will be in the documentation for JFrame, or the Java Tutorials.