Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / April 2006

Tip: Looking for answers? Try searching our database.

How to 'pack' a JPanel?

Thread view: 
Stephen Marjoribanks - 10 Apr 2006 12:49 GMT
I have a GUI made up of a number of JPanels within JPanels. The layout
and size of the top level of JPanels is controlled using a GridBagLayout
and this seems to be fine. The problem I am having is that some of the
JPanels within these top level JPanels (and the JPanels within those!!)
are not behaving as I would like. One of the bottom level JPanels
contains a JTable of 2 columns both of which have a preferredWidth and
maxWidth set. The problem is that although the size of the JTable is as
I want, it does not fill the whole JPanel within which it is contained
and so there is a large empty space left to the right of the JTable.
What is the best way to get round this, in a similar manner to the
'pack()' method which will still allow for the user to resize the window
without causing any nasty layout issues?

Thanks,
Steve
Brandon McCombs - 11 Apr 2006 04:28 GMT
> I have a GUI made up of a number of JPanels within JPanels. The layout
> and size of the top level of JPanels is controlled using a GridBagLayout
[quoted text clipped - 8 lines]
> 'pack()' method which will still allow for the user to resize the window
> without causing any nasty layout issues?

One thing is gbc.fill = GridBagConstraints.HORIZONTAL; and the other is
modifying your weightx value like gbc.weightx = 1;.  Lots of things can
happen when you start playing with those constraint values.
saj - 11 Apr 2006 07:36 GMT
hey man try using null layout instead of any other layout
manager....... it is not only the most flexible but also the most
powerful layout manager..... don't get stuck with those Flow or
GridBagLayout managers..........null layout is much better to
use......... although it is a little difficult if u don't use an IDE....
Bart Cremers - 11 Apr 2006 09:25 GMT
I must say I don't agree with this statement.

It's true that you need to learn the layout managers, but once you get
the basics worked out you will only have benefit in using them. Use the
null layout and then try resizing the frame and look what hapens.
Trying to keep you're gui looking good when the frame resizes is very
difficult, but when using layout managers they will do all the work for
you.

Layout managers have a very small learning curve for the benefits you
get from them.

Use them!!!

Bart
Paul Hamaker - 11 Apr 2006 09:30 GMT
Except that such an implementation won't adapt to different resolutions
automatically, unless you would want to code that, too.
--------------------
Paul Hamaker, SEMM, teaching ICT since 1987
http://javalessons.com
Paul Hamaker - 11 Apr 2006 09:34 GMT
Except that such an implementation won't adapt to different resolutions
automatically, unless you would want to code that, too.
--------------------
Paul Hamaker, SEMM, teaching ICT since 1987
http://javalessons.com
Bart Cremers - 11 Apr 2006 09:36 GMT
I must say I don't agree with this statement.

It's true that you need to learn the layout managers, but once you get
the basics worked out you will only have benefit in using them. Use the
null layout and then try resizing the frame and look what hapens.
Trying to keep you're gui looking good when the frame resizes is very
difficult, but when using layout managers they will do all the work for
you.

Layout managers have a very small learning curve for the benefits you
get from them.

Use them!!!

Bart
Roedy Green - 11 Apr 2006 19:00 GMT
>Layout managers have a very small learning curve for the benefits you
>get from them.

It is also much easier than you would think to write a custom layout
manager. That is preferable to using a null layout manager. It
separates the positioning logic. It makes the positioning logic
reusable.

see http://mindprod.com/jgloss/layout.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Bart Cremers - 11 Apr 2006 09:38 GMT
I must say I don't agree with this statement.

It's true that you need to learn the layout managers, but once you get
the basics worked out you will only have benefit in using them. Use the
null layout and then try resizing the frame and look what hapens.
Trying to keep you're gui looking good when the frame resizes is very
difficult, but when using layout managers they will do all the work for
you.

Layout managers have a very small learning curve for the benefits you
get from them.

Use them!!!

Bart
Thomas Weidenfeller - 11 Apr 2006 09:48 GMT
> hey man try using null layout instead of any other layout
> manager....... it is not only the most flexible but also the most
> powerful layout manager..... don't get stuck with those Flow or
> GridBagLayout managers..........null layout is much better to
> use......... although it is a little difficult if u don't use an IDE....

Oh sure - if you want to lose all cross-platform support. If you want to
lose support for more than one PLAF, and if you want to risk that a
simple VM change, a different set of fonts installed on some target
machine or just a different window manager blows up your layout. And if
you want to have to hand-code all your resizing behavior. Than, and only
then using no layout managers is a really great idea.

/Thomas
Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/

Paul Hamaker - 11 Apr 2006 10:47 GMT
Except that such an implementation won't adapt to different resolutions
automatically, unless you would want to code that, too.
--------------------
Paul Hamaker, SEMM, teaching ICT since 1987
http://javalessons.com
Stephen Marjoribanks - 11 Apr 2006 21:00 GMT
I've still had no luck with it at all, I'm completely at a loss as to
why I can't get it to behave how I want!! If I post the relevant
sections of code I would be very grateful if some of you could have a
look at it and point out any errors to me. The problem is that before I
added the JTable, the GUI set up exactly how I wanted, according to the
grid bag constraints I specified (or so I believe anyhow), but now I
have added the JTable, the JTable panel is much wider than it needs to
be, leaving empty space to the right of the table and mucking up the
layout of the other components in the GUI,

Many thanks,
Steve

code....

class SlopeSketchPanel extends JPanel
{
    // declare variables
    public JPanel sketchArea;
    public JPanel dataArea;
    public JPanel keyArea;
    public JPanel scaleArea;
    public JLabel layerLabel;
    public JLabel layerNo;
    // declare instances of objects created
    public SlopeGraphicsPanel slp;
    public DataTable dataTable;
//    public ScalePanel sp;
   
    // constructor
    SlopeSketchPanel()
    {
        // create instance of SlopGraphicsPanel class
        slp = new SlopeGraphicsPanel();
        dataTable = new DataTable();
//        sp = new ScalePanel();
       
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        sketchArea = new JPanel();
        keyArea = new JPanel();
        dataArea = new JPanel();
        scaleArea = new JPanel();
        setLayout(new GridBagLayout());
       
        // create sketch area panel
        sketchArea.setLayout(new BorderLayout());
   
sketchArea.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(15,15,15,15)));
        // add slope graphics panel
        sketchArea.add(slp, BorderLayout.CENTER);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 7;
        gridBagConstraints.gridheight = 7;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 70.0;
        gridBagConstraints.weighty = 70.0;
        add(sketchArea, gridBagConstraints);
       
        // create scale area panel
        scaleArea.setLayout(new BorderLayout());
        scaleArea.setBorder(BorderFactory.createEtchedBorder());
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 7;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 30.0;
        gridBagConstraints.weighty = 30.0;
        add(scaleArea, gridBagConstraints);
       
        // create key area panel
        keyArea.setLayout(new FlowLayout());
        keyArea.setBorder(BorderFactory.createEtchedBorder());
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 7;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 40.0;
        gridBagConstraints.weighty = 30.0;
        add(keyArea, gridBagConstraints);
       
        // create data display area panel
        dataArea.setLayout(new BorderLayout());
        dataArea.setBorder(BorderFactory.createEtchedBorder());
        // add data table
        dataArea.add(dataTable, BorderLayout.CENTER);
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 7;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.gridheight = 10;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 30.0;
        gridBagConstraints.weighty = 70.0;
        add(dataArea, gridBagConstraints);
    }
}

class DataTable extends JPanel
{
    public DataTableModel tableModel;
   
    DataTable()
    {
        this.setLayout(new BorderLayout());
        tableModel = new DataTableModel();
        JTable table = new JTable(tableModel);
        TableColumn propertyColumn = table.getColumnModel().getColumn(0);
        DataTableCellRenderer cellRenderer = new DataTableCellRenderer();
        propertyColumn.setCellRenderer(cellRenderer);
        propertyColumn.setMinWidth(130);
        propertyColumn.setMaxWidth(130);
        propertyColumn.setPreferredWidth(130);
        TableColumn valueColumn = table.getColumnModel().getColumn(1);
        valueColumn.setMinWidth(175);
        valueColumn.setMaxWidth(175);
        valueColumn.setPreferredWidth(175);
        // set table preferences
        table.getTableHeader().setResizingAllowed(false);
        table.getTableHeader().setReorderingAllowed(false);
        table.setCellSelectionEnabled(false);
        JScrollPane tableScroll = new JScrollPane(table);
        add(tableScroll, BorderLayout.CENTER);
       
    }
}

class DataTableModel extends AbstractTableModel
{
    // create data model
    String[] columnNames = {"Property", "Value"};
    Class[] columnType = {String.class, String.class};
    Object[][] data = {{"Layer Number", "layerNumber"},
                        {"", ""},
                        {"Soil Parameters", ""},
                        {"Cu", "cu"},
                        {"Phi", "phi"},
                        {"Cohesion", "cohesion"},
                        {"Bulk density", "bulkDensity"},
                        {"Dry density", "dryDensity"},
                        {"Submerged density", "submergedDensity"},
                        {"Moisture content", "moistureContent"},
                        {"Liquid limit", "liquidLimit"},
                        {"Plastic limit", "plasticLimit"},
                        {"Notes", "notes"},
                        {"", ""},
                        {"Main Constituent", ""},
                        {"Type", "mainType"},
                        {"Name", "mainName"},
                        {"Strength", "mainStrength"},
                        {"Consistency", "mainConsistency"},
                        {"Grain size", "mainGrainSize"},
                        {"Main colour", "mainMainColour"},
                        {"Secondary colour", "mainSecondaryColour"},
                        {"Plasticity", "mainPlasticity"},
                        {"Comments", "mainComments"},
                        {"", ""},
                        {"Secondary Constituent", ""},
                        {"Type", "secondType"},
                        {"Name", "secondName"},
                        {"Strength", "secondStrength"},
                        {"Consistency", "secondConsistency"},
                        {"Grain size", "secondGrainSize"},
                        {"Main colour", "secondMainColour"},
                        {"Secondary colour", "secondSecondaryColour"},
                        {"Plasticity", "secondPlasticity"},
                        {"Comments", "secondComments"},
                        {"", ""},
                        {"Minor Constituent", ""},
                        {"Type", "minorType"},
                        {"Name", "minorName"},
                        {"Strength", "minorStrength"},
                        {"Consistency", "minorConsistency"},
                        {"Grain size", "minorGrainSize"},
                        {"Main colour", "minorMainColour"},
                        {"Secondary colour", "minorSecondaryColour"},
                        {"Plasticity", "minorPlasticity"},
                        {"Comments", "minorComments"}};
   
    public int getColumnCount()
    {
        return columnNames.length;
    }
   
    public int getRowCount()
    {
        return data.length;
    }
   
    public String getColumnName(int col)
    {
        return columnNames[col];
    }
   
    public Object getValueAt(int row, int col)
    {
        return data[row][col];
    }
   
    public Class getColumnClass(int c)
    {
        return columnType[c];
    }
   
    public boolean isCellEditable(int rowIndex, int vColIndex)
    {
        return false;
    }
   
    public void setValueAt(Object aValue, int r, int c)
    {
        data[r][c] = aValue;
    }
   
    public void updateData()
    {
        fireTableDataChanged();
    }
}

class DataTableCellRenderer extends JLabel implements TableCellRenderer
{
    DataTableCellRenderer()
    {
        setOpaque(true);
    }
   
    public Component getTableCellRendererComponent(JTable table, Object
value, boolean isSelected, boolean hasFocus, int row, int col)
    {
        setBackground(Color.lightGray);
        if (row == 0 || row == 2 || row == 14 || row == 25 || row == 36)
        {
            setFont(new Font("Dialog", Font.BOLD, 12));
            setText(value.toString());
        }
        else
        {
            setFont(new Font("Dialog", Font.PLAIN, 12));
            setText(value.toString());
        }
        return this;
    }
}
Bart Cremers - 12 Apr 2006 07:44 GMT
Your problem has nothing to do with the GridBagLayout, although I would
suggest you pay more attention on how you work with the weightx and
weighty properties.

The white space to the left of the table is simply the way a JTable
defines the size of the scrollable viewport. All tables start with a
default viewport size of 450x400 which of course is to large for your
table as you fix the column sizes to a combined total of 305 pixels.

Add
       table.setPreferredScrollableViewportSize(new Dimension(305,
400));

to the table settings and the white area is gone.

Regards,

Bart
Stephen Marjoribanks - 12 Apr 2006 11:58 GMT
> Your problem has nothing to do with the GridBagLayout, although I would
> suggest you pay more attention on how you work with the weightx and
[quoted text clipped - 14 lines]
>
> Bart

Ok thank you very much for your help, I have fixed it now although
strangely if I specify a width of 305 in the dimension it still leaves
white space, it seems a width of around 100 fits roughly the correct size?!
Also if you don't mind could you point out what you mean when you said I
should pay more attention to the weightx and weighty properties in
GridBagLayout because I have only really just started using it.

Many thanks
Steve
Stephen Marjoribanks - 12 Apr 2006 12:30 GMT
>> Your problem has nothing to do with the GridBagLayout, although I would
>> suggest you pay more attention on how you work with the weightx and
[quoted text clipped - 24 lines]
> Many thanks
> Steve

Also, there still seems to be something slightly funny. No matter what i
set the prefferred width of the table viewport to if i resize the frame
and make it larger, some white space appears again?
Bart Cremers - 12 Apr 2006 12:33 GMT
The white area of 100 pixels depends on how you size the containing
frame. I used pack() and did not have any white space.

What I meant with the weightx and weighty is that you should think
about which components deserve extra space if there's some left and how
much of the extra space they should get. For must GUI's it works best
if a single part of the GUI takes up all the extra space and the other
parts are left to occupy only their preferred space.

Also, you might consider to change the layout to use some panels using
borderlayout and stack those instead of using a gridbaglayout. I'm not
saying you should not use gridbaglayout, but your gui looks like it
might be a candidate for the borderlayout approach. Using it will save
you much gridbag headaches.

Bart
Stephen Marjoribanks - 12 Apr 2006 13:13 GMT
> The white area of 100 pixels depends on how you size the containing
> frame. I used pack() and did not have any white space.

I mean the white space is within the scrollable viewport. So it is the
size of the viewport which is causing it, even thought it is supposed to
have been given a preferred size?
I can't use pack because it is contained within a JPanel as opposed to a
JFrame.

Steve
Bart Cremers - 12 Apr 2006 13:28 GMT
I imagined something like that, that's why I said my pack did work on
for you it did not work. You're dependant on the parent container on
how much size the components get.
And that's also why I told you to take a close look at the weight...
settings and try to understand fully what they will do (maybe put the
weightx to 0.0) for the table.

Bart
Stephen Marjoribanks - 12 Apr 2006 14:17 GMT
> I imagined something like that, that's why I said my pack did work on
> for you it did not work. You're dependant on the parent container on
[quoted text clipped - 4 lines]
>
> Bart

Ah, ok, I think I see what you're getting at, I'll have a play around
with it

Steve


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.