tags:

views:

122

answers:

3

This code, when run, will make a window but not at the specified dimensions. What is wrong with it?

import javax.swing.*;
import java.awt.*;

public class Windowing {
    void JFrame(){
        JFrame frames = new JFrame("Total recall");
        frames.setSize(1000,8000);
        frames.setVisible(true);
        frames.pack();
        //Buttons push = new Buttons();
        //((Buttons) push).buttons();
        JTextField wager = new JTextField(1);
        wager.setSize(100,200);
        wager.setVisible(true);
        wager.setLocation(100, 200);
        frames.add(wager);
        //frames.add(push);
    }
}
+3  A: 

You could remove the call to frames.pack(); it overrides the previously set frame size.

However, what you really want to do is remove the frames.setSize(1000,8000) and move frames.pack() down to the bottom of the method; that will ensure that the frame is big enough to display its contents but not too big to fit on the screen.

If you call pack before adding anything to the frame (like you are doing now), it will make the window extremely small; it's probably appearing near the upper left of your screen, but you won't notice it unless you know where to look.

Michael Myers
Could he move the `setSize()` call to after the `pack()` call?
Loadmaster
Sure, but that would make the frame too big to fit on the screen. And it's pointless to use *both* methods of setting the frame's size.
Michael Myers
+1  A: 

Try to use setPreferredSize(Dimension) instead.

Erkan Haspulat
+1  A: 

It looks like you have a number of "opportunity areas" here.

  • To start, it seems like you set frame size to 1000x8000 because you didn't see any change right?

  • Secondly you call setVisible on the textField because you didn't see that either.

  • And finally you're setting the size of the textfield ( I guess because you're seeing it take the whole frame )

The problem here is that you have to invoke pack and setVisible at the end of the construction. Also, you have to learn how to use layout managers and frames.

Swing, is very powerful, but it is a bit hard to grasp at the beginning.

These two links will be helpful:

I've changed your code and the result looks like this:

alt text

Here's the modified source code.

import javax.swing.*;
import java.awt.*;

public class Windowing {
    public static void main( String [] args ) {
        Windowing windowing = new Windowing();
        windowing.showFrame();
    }
    void showFrame(){
        JFrame frame = new JFrame("Total recall");
        JButton push = new JButton("Push");
        JTextField wager = new JTextField(15);

        // Panels do have "FlowLayout"
        JPanel panel = new JPanel();
        panel.add(wager);
        panel.add(push);

        frame.add( panel );
        frame.pack();
        frame.setVisible(true);

    }
}
OscarRyz