?
Solved

Problems with getHeight()

Posted on 2006-05-31
24
Medium Priority
?
291 Views
Last Modified: 2010-03-31

I hard-code a Dimension for a JPanel and print out its height.
The chunk of code below is literal -- nothing comes between the setting of the sizes and the println.
            
code: ----------------------------------
            centrePanel = new JPanel();
                  centrePanel.setLayout( new BoxLayout( centrePanel, BoxLayout.Y_AXIS ) );
                  centrePanel.setPreferredSize( new Dimension( 170, 300 ) );
                  centrePanel.setMinimumSize( new Dimension( 170, 300 ) );
                  centrePanel.setMaximumSize( new Dimension( 170, 300 ) );

System.out.println( "[After setting Dimension]: centrePanel.getHeight() = " + centrePanel.getHeight() );
System.out.println( "" );
 end code ----------------------------------

The result:
"[After setting Dimension]: centrePanel.getHeight() = 0"


Tests at several other points in the program also return 0, then one test results in a height of 636.
The GUI assembles and displays properly except for this one component.

Is the getHeight() method just unreliable, or is there some secret to implementing it properly?



0
Comment
Question by:javaQQ
  • 8
  • 6
  • 5
  • +2
21 Comments
 
LVL 2

Expert Comment

by:appxpete
ID: 16801330
I've always overridden the getPreferredSize() method myself if I want to absolutely force the value.  I think the layout managers also try to set the height values.

centrePanel = new JPanel() {
    Dimension getPreferredSize() {
        return new Dimension(170,300);
    }
};
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16801432
try to call setSize() also :
    Dimension dim=new Dimension(170,300);
    centrePanel.setPreferredSize( dim );
    centrePanel.setMinimumSize( dim );
    centrePanel.setMaximumSize( dim );
    centrePanel.setSize( dim );

>> centrePanel.setLayout( new BoxLayout( centrePanel, BoxLayout.Y_AXIS ) );
What's the layout of the Container (where you added the centrePanel component) ?

>> I've always overridden the getPreferredSize() method myself
This is necessary for AWT, but with Swing, it's useless and can malfunction if you miswrite the method name (e.g. getPreferedSize instead of getPreferredSize) without compilation error. Whereas calling setPreferredSize will generate compilation error if you miswrite it.
0
 

Author Comment

by:javaQQ
ID: 16801471
Hi  appxpete;

When I try your code, the compliler responds:

"getPreferredSize() in  cannot override getPreferredSize() in javax.swing.JComponent; attempting to assign weaker access privileges; was public
    Dimension getPreferredSize() {"
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 13

Expert Comment

by:Webstorm
ID: 16801516
then :

centrePanel = new JPanel() {
    public Dimension getPreferredSize() {
        return new Dimension(170,300);
    }
};
0
 

Author Comment

by:javaQQ
ID: 16801707
Hi  Webstorm;

>> What's the layout of the Container (where you added the centrePanel component) ?

The component is a JPanel. Its layout is BorderLayout. The centrePanel is added BorderLayour.CENTER
0
 

Author Comment

by:javaQQ
ID: 16801735

Hi  again Webstorm;

>>     centrePanel.setSize( dim );

This works initially, but somewhere along the line the value pops up to 636, without a command
0
 
LVL 2

Expert Comment

by:appxpete
ID: 16801762
Did you try adding the 'public' in front of the method definition?

public Dimension getPreferredSize() {

0
 

Author Comment

by:javaQQ
ID: 16801791


>> Did you try adding the 'public' in front of the method definition?

public Dimension getPreferredSize() {

Yes. No change
0
 
LVL 2

Expert Comment

by:appxpete
ID: 16801817
No change as in you get the same compiler error ...."was public"?
0
 
LVL 13

Accepted Solution

by:
Webstorm earned 500 total points
ID: 16801867
If you only have 1 component in at BorderLayour.CENTER, then you need to add dummy ones at BorderLayour.NORTH,BorderLayour.SOUTH,BorderLayour.EAST, and BorderLayour.WEST.
0
 

Author Comment

by:javaQQ
ID: 16801873
>> No change as in you get the same compiler error ...."was public"?

Sorry about the ambiguity. The code compiles. Adding "public" does not change the results of the getHeight() call.
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16801874
(  BorderLayour  ->  BorderLayout  )
0
 
LVL 2

Expert Comment

by:appxpete
ID: 16801900
It doesn't seem like you should have to do this but this would force it to always return what you want.

centrePanel = new JPanel() {
    public double getHeight() {
        return 300;
    }
};
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16801933
Or if you don't want to add dummy component at N,E,S,W in BorderLayout, you can override the layout to calculate component position yourself :

     <container> = new <class> () {
             public void doLayout()
             {
                  Component[] comp=getComponents();
                  Dimension d=getSize(), dc;
                  if ((comp.length==0)||(d==null)) return;
                  dc=comp.getPreferredSize();
                  comp.setBounds( (d.width-dc.width)/2, (d.height-dc.height)/2, dc.width, dc.height );
             }
       }
     <container>.setLayout(null);

0
 
LVL 2

Expert Comment

by:appxpete
ID: 16801935
Actually, webstorm is right.  You should use the layout manager properly, not override methods() in place of proper layout manager usage.
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16801945
      };     // <----
     <container>.setLayout(null);
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16802272
another correction:
                  dc=comp[0].getPreferredSize();
                  comp[0].setBounds( (d.width-dc.width)/2, (d.height-dc.height)/2, dc.width, dc.height );
0
 
LVL 92

Expert Comment

by:objects
ID: 16802566
> The component is a JPanel. Its layout is BorderLayout. The centrePanel is added BorderLayour.CENTER

Add it to North or South instead.
CENTER does not use preferred size
0
 
LVL 2

Expert Comment

by:seet82
ID: 16804062
always read the java documentation regarding the size issues
from my experience, not all layout manager will 'respect' the min,max,prefered size
some will enforce/use only min, some max, some both...blah blah blah...you get the point

btw, to appxpete,
wat's the point of overridding getPreferedSize and getHeight???
your concept is totally wrong. when you call getHeight, what you want to get is the height of the JPanel, not a value that you defined....
it's like writing a Wallet class. wallet.getAmount() returns 10000000000000 (well, u hardcode the value) but in actual fact, the actual amount is 0 (well it does makes me happy to have so much money in my wallet)
0
 
LVL 2

Expert Comment

by:appxpete
ID: 16807049
His original complaint was that he was trying to set the object to have an exact size and checking getHeight() later reported a size other than what he set it to.  I agree that a literal return value is pretty useless unless you always want it to be that size.  I don't use a literal return value for what I do but a variation.  I work with an application that requires absolute control over some object locations and sizes.  Any fiddling by other code, like layout managers, causes big problems for these objects.  Our solution was to create our own size and location variables inside each object and use our own methods to set them.  Then override the getPreferredSize() and getLocation() methods to report our values.  I was just showing an overly simplified version to show that he could override the method to always return a value he wanted.

This is probably a better example:

import java.awt.Dimension;
import javax.swing.JPanel;

public final class PetePanel extends JPanel {
    private Dimension mySize;

    public void setMySize(int width, int height) {
        mySize = new Dimension( width, height );
    }

    public Dimension getPreferredSize() {
        if( mySize == null )
            return super.getPreferredSize();
        else
            return mySize;
    }
}
0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16999917
I suggest accepting http:#16801867
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month16 days, 7 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question