Help on setting size of JFrame?

Discussion in 'Java' started by A Watcher, Feb 22, 2008.

  1. A Watcher

    A Watcher Guest

    I'm trying to develop a slider control for an application. The slider
    would be in a new Window. I can't seem to set the size of it. Here
    is the code. Setting the location works, but not the size. In this
    example SliderDemo2 is a class that extends JPanel. What am I doing
    wrong? I've tried setting the size of the JPanel too, without
    success.

    public static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("SliderDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Wrapper.slider = new SliderDemo2();
    frame.setLocation(600,300);
    Dimension minSize = new Dimension(400,200);
    frame.setMinimumSize(minSize);

    //Add content to the window.
    frame.add(Wrapper.slider, BorderLayout.WEST);

    //Display the window.
    frame.pack();
    frame.setVisible(true);

    }
     
    A Watcher, Feb 22, 2008
    #1
    1. Advertisements

  2. A Watcher

    A Watcher Guest

    I also tried frame.setSize(600,300);

    That didn't work either.
     
    A Watcher, Feb 22, 2008
    #2
    1. Advertisements

  3. ..pack() uses the preferredSize of each component to do its calculations
     
    thenerdwonder, Feb 23, 2008
    #3
  4. A Watcher

    A Watcher Guest


    Thanks!

    I knew it had to be something simple
     
    A Watcher, Feb 23, 2008
    #4
  5. A Watcher

    Mark Space Guest

    You can also use pack() first to size everything, then use setSize to
    make certain stuff larger. setSize won't make things smaller, it just
    makes them bigger (check the Java Doc, it says that right there in the
    description). That's a simple way of setting the size of objects.

    You can also make a new slider of your own like so:

    public class MySlider extends javax.swing.JSlider {

    }

    and override the getPreferredSize() method. Or you could use a Layout
    Manager that was a bit more sophisticated and didn't just smash
    everything down to the preferred size. Either of these latter two
    options is probably a better long term solution.
     
    Mark Space, Feb 23, 2008
    #5
  6. It's also fragile. If the layout manager decides to recalculate
    everything, you go back to the default preferredSize
    Which is better than just calling setPreferredSize() how? Creating a
    subclass just to resize a component is silly at best.
    Sure, or you could learn how Swing works and use it properly.
     
    thenerdwonder, Feb 23, 2008
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.