Sizing JPanels?

Here's some code...
Can anyone tell me why the JPanel size doesn't seem to work like I want it to? (ie, in this case it should fill the container window)
import javax.swing.*;
import java.awt.*;
public class WindowTest extends JFrame {
void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy)
  gbc.gridx = gx;
  gbc.gridy = gy;
  gbc.gridwidth = gw;
  gbc.gridheight = gh;
  gbc.weightx = wx;
  gbc.weighty = wy;
public WindowTest()
  super("Test Window");
  Container c = getContentPane();
  c.setBackground(Color.black);
  setSize(600, 480);
  JPanel firstPanel = new JPanel();
  firstPanel.setSize(600, 480);
  GridBagLayout gridbag = new GridBagLayout();
  GridBagConstraints constraints = new GridBagConstraints();
  c.setLayout(gridbag);
  constraints.fill = GridBagConstraints.CENTER;
  firstPanel.setLayout(gridbag);
  firstPanel.setBackground(Color.red);
  //'Enter Text Below' Label
  buildConstraints(constraints, 1, 1, 1, 1, 0, 0);
  JLabel label1 = new JLabel("Enter text below");
  gridbag.setConstraints(label1, constraints);
  firstPanel.add(label1);
  //Text Entry Field
  buildConstraints(constraints, 1, 2, 1, 1, 0, 0);
  TextField textfield1 = new TextField("", 50);
  gridbag.setConstraints(textfield1, constraints);
  firstPanel.add(textfield1);
  c.add(firstPanel);
  show();
public static void main(String args[])
  WindowTest wt = new WindowTest();
}

Use setPreferredSize() instead of setSize().

Similar Messages

  • How to senter a JPanel on a parent container

    Hi,
    I have a fixed sized JPanel that I want to add to the center of a container. I would like my JPanel's center to be fixed to the center of the container.
    I have tried to use GridBagLayout with a GridbagConstraint like follows:
    GridBagLayout gridbag = new GridBagLayout();
    getContentPane().setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = c.CENTER;
    SubPanel subPanel = new SubPanel();
    gridbag.setConstraints(subPanel, c);
    getContentPane().add(subPanel);
    setSize(400, 500);
    setVisible(true);
    But this results in the upper left corner of my JPanel being put in the center of the container. Does anyone know how to get the center of my JPanel being placed in the center?
    Best regards
    // Johan

    how about flowlayout?
    this.setLayout( new Flowlayout( Flowlayout.CENTER ) );
    this.add( subPanel );
    This might put it at the center at the top though.
    Another way would be to use GridLayout and set the grids, when you add your panel it Should size the cells equal to your largest component which would be the JPanel, then just add blank JLabels to the other cells and add your subpanel to the center cell, that my work better.

  • Inherited JPanels inserted to GridLayout - panel size problem

    Hello,
    I'm not sure if I implemented it correctly, however I'm trying to have different-sized JPanels inserted to GridLayout. JPanels are inherited from base JPanel class. Shortly:
    public class CMyBasePanel extends javax.swing.JPanel
    public class CPanelBig extends CMyBasePanel
        this.setLayout(null);
        this.setPreferredSize(new java.awt.Dimension(642, 138));
    public class CPanelSmall extends CMyBasePanel
        this.setLayout(null);
        this.setPreferredSize(new java.awt.Dimension(642, 50));
    }and I'm trying to insert them that way:
    int numPanels = this.panels.size();    // Vector of CMyBasePanel
    jPanelSteps = new JPanel();
    jPanelSteps.setLayout(new GridLayout(numPanels, 1));
    for (int i = 0; i < numPanels; i++)
        CMyBasePanel onePanel = (CMyBasePanel)this.panels.get(i);
        jPanelSteps.add(onePanel);
    jScrollPaneSteps.setViewportView(jPanelSteps);
    jScrollPaneSteps.revalidate();
    jScrollPaneSteps.repaint();This method shows created panels correctly, but the panel height is constant for all panels, even if they have different Dimensions set in the constructor.
    Full case can be downloaded here: http://slajerek.demon.pl/others/bugs/JPanelInheritProblem.tar.gz
    After starting the case just right click on empty space to show popup menu and add two different panels, size of already added panels is changed respectively (add 10 small panels, and then big one). Java version: Java(TM) SE Runtime Environment (build 1.6.0_02-b05), Linux
    is this a bug or bad implementation? I thought that if I change one of the parameters in the inherited class I'm not changing the base class. For me it seems that the panel size is declared "static"? how to avoid this problem and have different heights for panels?

    yea GridLayout resizes components to fit in the grid, where all the grids are the same size. So if you have one big component in a grid, then the components in the other grid will be resized i believe.

  • Set size of jPanel

    Hi i've create a jForm in netbeans. To this I have added a scrollpane containing a jPanel called PrintPreview. (I have to do this rather than use the automated preview of printUtilities because of some items I need removed from the original jPanel before printing).
    I need to set the size of the PrintPreview jPanel as it's instantiated. I have the dimensions created from another class called "Gbl".
    In the constructor is the following:
    /** Creates new form PrintPreview */
    public PrintPreview() {
    PreviewPanel.setPreferredSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
    PreviewPanel.setMaximumSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
    PreviewPanel.setMinimumSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
    Window.pack();
    initComponents();
    this.setLocationRelativeTo(null);
    // ADD CODE - COLLECT DRAWING FROM ARRAY
    PreviewPanel.repaint();
    I would like the jPanel set to these dimensions however I would also like the scrollPane to remain at it's standard size so I can scroll the diagram as necessary.
    Could you please tell me where I am going wrong? The three setSize lines are flagged as erroneous. The dimensions are int and have tried double.
    Any advice is good...
    Thanks

    Ok I'm going to add onto this thread because it still relates to the original problem. setting size of jPanel.
    Some details first:
    OS - Ubuntu Gutsy 7.10
    Kernel - 2.6.22-14-generic
    NB - v5.5.1
    Java version - java version "1.5.0" / gij (GNU libgcj) version 4.2.1 (Ubuntu 4.2.1-5ubuntu5)
    Research:
    I have been trawling the net for days trying to resolve this but I am struggling to find anything specific to my problem. I keep finding general methods using given NB facilities. I've also scoured a couple of my Java books but of course they're not totally relevant to NetBeans. I've practiced using the forum this afternoon to find things but with my lack of knowledge using both forums and java has left me a little bamboozled. I've been working on this problem for a couple of days now and achieved very little.
    My specific problem is this:
    I have a JFrame GUI. Inside that I have a jTabbedPane containing a jScrollPane containing a jPanel. I would like to have the jPanel display at A4 size relevant to the screen it is displayed on. e.g. I have a separate global class "Gbl" that calculates the dimensions based on current dpi and then creates the necessary measurements to feed to my preferred size function.
    I have tried implementing the preferred size method to the constructor and have also tried adding it to all four ways to enter bespoke code to NetBeans' autogenerated code. (Pre-init, Post-init, Pre-creation and Post-creation code) To no avail. Nothing changes on screen.
    The code I am trying to enter is as follows:
    // Set preferred size of user-drawing-area (jPanel1)
    jPanel1.setPreferredSize(new java.awt.Dimension(600,500));
    jPanel1.setMaximumSize(new java.awt.Dimension(600,500));
    jPanel1.setMinimumSize(new java.awt.Dimension(600,500));
    // Set preferred size of jPanel1 container (jScrollPane1)
    jScrollPane1.setPreferredSize(new java.awt.Dimension(600,500));
    jScrollPane1.setMaximumSize(new java.awt.Dimension(600,500));
    jScrollPane1.setMinimumSize(new java.awt.Dimension(600,500));
    // Set preferred size of the jScrollPane1 container (mainTabView(Tabbed pane))
    mainTabView.setPreferredSize(new java.awt.Dimension(600,500));
    mainTabView.setMaximumSize(new java.awt.Dimension(600,500));
    mainTabView.setMinimumSize(new java.awt.Dimension(600,500));
    I am using absolute values here to omit any error getting the variables from my Global class. If it works I will add them and test again.
    Ideally, I would like the jPanel to be set to an A4 size yet have the containers at a smaller more "screen-manageable" size (With scroll bars). Then if the GUI is maximized, then it only expands to the full size of the A4 sized jPanel if possible.
    Of course, this may not be possible or there may be a far better method for doing this, however I am really stumped. I've had some good advice this afternoon of whihc has opened may eyes some. Although, I have made no headway so far. I hope the above follows site-rules and gives enough information to resolve this issue. I'm losing hair rapidly!
    I'm grateful for any advice given. Thank You

  • Its seems impossible to center a fixed size image on a container

    Hi,
    I have a fixed sized JPanel that I want to add to the center of a container. I would like my JPanel's center to be fixed to the center of the container.
    I have tried to use GridBagLayout with a GridbagConstraint like follows:
    GridBagLayout gridbag = new GridBagLayout();
    getContentPane().setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = c.CENTER;
    SubPanel subPanel = new SubPanel();
    gridbag.setConstraints(subPanel, c);
    getContentPane().add(subPanel);
    setSize(400, 500);
    setVisible(true);
    But this results in the upper left corner of my JPanel being put in the center of the container. Does anyone know how to get the center of my JPanel being placed in the center?
    The following two suggestions does not work:
    1) This solution put my panel two the right of the center:
    this.setLayout( new Flowlayout( Flowlayout.CENTER ) );
    this.add( subPanel );
    2) This does only work in the special case that the width of my panel is a third of the width of the container:
    Use GridLayout and set the grids, when you add your panel it Should size the cells equal to your largest component which would be the JPanel, then just add blank JLabels to the other cells and add your subpanel to the center cell.

    this is some sample code. It has not been compiled like this, but there should only be minor problems. if it does not work, just post a message...
    ok, here we go:
    import javax.swing.*;
    import java.awt.*;
    public class CenterLayout implements LayoutManager2 {
    // make sure that only one child is added to the container
    public void addLayoutComponent(Component comp, Object constraints) {
    if( comp.getParent().getComponentCount() > 1 )throw new RuntimeException("only one child allowed for this layout");
    // as big as you want...
    public Dimension maximumLayoutSize(Container target) {
    return new Dimension( Integer.MAX_VALUE, Integer.MAX_VALUE);
    public float getLayoutAlignmentX(Container target) {
    return .5f;
    public float getLayoutAlignmentY(Container target) {
    return .5f;
    public void invalidateLayout(Container target) {
    public void addLayoutComponent(String name, Component comp) {
    addLayoutComponent(comp, name);
    public void removeLayoutComponent(Component comp) {
    // this assumes that the preferred size is the preferred size of the single child plus insets...
    public Dimension preferredLayoutSize(Container parent) {
    Insets insets = parent.getInsets();
    int w = insets.left + insets.right;
    int h = insets.top + insets.bottom;
    if (parent.getComponentCount() > 0 ) {
    Dimension childSize = parent.getComponent(0).getPreferredSize();
    return new Dimension(childSize.width + w, childSize.height + h );
    } else {
    return new Dimension(w,h);
    // this assumes that the minimum size is only the minimum size of the single child. if you want insets
    // considered for minimum size, add them here
    public Dimension minimumLayoutSize(Container parent) {
    if (parent.getComponentCount() > 0 ) {
    return parent.getComponent(0).getMinimumSize();
    } else {
    return new Dimension(0,0);
    // this is the important stuff, calculating childs
    // position. It always sets the child to its
    // preferred size and centers it.
    // there may be better strategies handling the case
    // that the containers dimension are smaller than its
    // childs dimensions. you may peek, if the child may be
    // scaled to fit in considering the minimum size of the child.
    // once started, layoutmanager can be improved with
    // more sophisticated algorithms ever on, go and paly
    // around with it :-)
    public void layoutContainer(Container parent) {
    if( parent.getComponentCount() > 0 ){
    Component child = parent.getComponent(0);
    Insets insets = parent.getInsets();
    Dimension size = parent.getSize();
    size.width = size.width - insets.left - insets.right;
    size.height = size.height - insets.top - insets.bottom;
    // put in child scaling here, if needed
    child.setSize(child.getPreferredSize());
    int x = insets.left + (int) ( (size.width - child.getWidth() )/2);
    int y = insets.top + (int) ( (size.height - child.getHeight() )/2);
    child.setLocation(x,y);
    public static void main(String[] args ) {
    JFrame f = new JFrame();
    f.getContentPane().setLayout(new CenterLayout() );
    f.getContentPane().add( new JButton("hello") );
    f.setSize( 200, 200 );
    f.setVisible(true);
    }

  • Problem with JPanel sizing!

    Hi,
    Just having a bit of difficulty with the sizing of JPanels. For example, if I create a JPanel and add it to a Frame, no matter what I set the size to the JPanel fills the entire Frame. I don't really know whats going on here and I'm just making guesses! If anyone has a good resource on the whole sizing thing or can point out what I'm doing wrong, that would be great. Thanks!
    // Constructor
    public void ClassName()
            mainWindow = new JFrame();
            mainWindow.setSize(mainWindowWidth, mainWindowHeight);
            mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel aPanel = new JPanel();
            aPanel.setSize(mainWindowWidth/2,mainWindowHeight/2); );
            aPanel.setBackground(Color.GREEN);
            mainWindow.add(aPanel);
            mainWindow.validate();
    }Edited by: LeWalrus on May 18, 2009 5:03 AM

    By default, JFrame uses a BorderLayout which gives the center component (your panel in this case) all available height and width.
    For absolute positioning you need to use a null layout.
    If you want a layout manager that can let your panel fill half the height/width, I think it might be possible with GridBagLayout or more recommended MiGLayout (but that adds a third party jar dependency).
    See the [layout tutorial|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html].

  • Question about relative sizing on JPanels

    Hi,
    My question is about relative sizing on components that are not drawn yet. For example I want to draw a JLabel on the 3rd quarter height of a JPanel. But JPanel's height is 0 as long as it is not drawn on the screen. Here is a sample code:
    JPanel activityPnl = new JPanel();
    private void buildActivityPnl(){
            //setting JPanel's look and feel
            activityPnl.setLayout(null);
            activityPnl.setBackground(Color.WHITE);
            int someValue = 30;  // I use this value to decide the width of my JPanel
            activityPnl.setPreferredSize(new Dimension(someValue, 80));
            //The JLabel's height is 1 pixel and its width is equal to the JPanel's width. I want to draw it on the 3/4 of the JPanel's height
            JLabel timeline = new JLabel();
            timeline.setOpaque(true);
            timeline.setBackground(Color.RED);
            timeline.setBounds(0, (activityPnl.getSize().height * 75) / 100 , someValue , 1);
            activityPnl.add(timeline);
        }Thanks a lot for your help
    SD
    Edited by: swingDeveloper on Feb 24, 2010 11:41 PM

    And use a layout manager. It can adjust automatically for a change in the frame size.
    Read the Swing tutorial on Using Layout Managers for examples of the different layout managers.

  • Problems sizing multiple JPanels.

    I'm writing a survey program that needs to be formatted to a certain size. I'm using calls to panel.setsize( ) to set the size to 800 x 600.
    I have nine JPanels as globals, all of which are created and "packed" initially. These JPanels are supposed to display in a global JFrame, one at a time. After each "next button" click I call frame.remove(panel) to remove the current panel and frame.add(panel) to add the next. Then I call pack again.
    Everything works fine until looping from the final panel to the first. Upon doing so all of the elements in the JPanel disappear, (although hovering over the invisible elements makes them reappear.)
    Is there anything I'm doing wrong?

    Well, calling repaint after pack seemed to solve the problem.
    Does anyone care to provide insight as to why?
    Thanks.

  • Sizing a JPanel on its contents

    Hi everybody,
    Does anyone know of a way to resize a JPanel around its contents? I have a panel that will be filled with 3, 5, or 7 lines of text, depending on a button click, and I'd like the panel to size appropriately on the button click. Is there a way to do this? I already have working code, working buttons, working lines, everything, but I just don't know how to do the resizing on demand. If anyone could point me in the right direction, I'd appreciate it.
    Thanks,
    Jezzica85

    Thanks Darryl,
    It looks like you posted just ahead of me, I was whipping up a SSCCE. For some reason, revalidate() isn't doing the job; it's probably something weird I'm doing, maybe this will help :
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class ResizeTest extends JPanel {
        private int entries;
        private static final long serialVersionUID = 5290537936355330083L;
        public ResizeTest( int number ) {
            entries = number;
            create();
        public void changeEntries( int entries ) {
            this.entries = entries;
            removeAll();
            create();
            revalidate();
            repaint();
        private void create() {
            setLayout( new GridLayout( entries, 1 ) );
            for( int i = 0; i < entries; i++ ) { add( new JLabel( "Line" ) ); }
            revalidate();
        // testing
        public static void main( String args[] ) {
            final ResizeTest panel = new ResizeTest(5);
            JPanel buttonPanel = new JPanel( new GridLayout( 1, 7 ) );
            for( int i = 3; i <= 15; i+=2 ) {
                JButton button = new JButton( "Change to " + i );
                final int blah = i;
                button.addActionListener( new ActionListener() {
                    public void actionPerformed( ActionEvent e ) {
                        panel.changeEntries( blah );
                buttonPanel.add( button );
            JFrame frame = new JFrame();
            frame.setLayout( new BorderLayout() );
            frame.add( panel );
            frame.add( buttonPanel, BorderLayout.SOUTH );
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
    }Thanks,
    Jezzica85

  • Sizing a jlist within a jpanel

    Hi,
    I'm writing a jpanel tjhat contains a jlist object at its center. Now, when I place the jpanel within a JFrame the panel grows to eat all the available space (I can see this thanks to the border of the panel), while the JList remains at a very small size regarding the jpanel. I'd like to have the jlist to resize itself to occupy all the
    jpanel size. The following is the code that shows it. Any idea about how to achieve this?
    Thanks,
    Luca
    public class ListPanel extends JPanel{
        protected JList myList;
    public AgletListPanel(){
            super();
            this.setLayout(new FlowLayout(FlowLayout.CENTER));
            this.listModel = new DefaultListModel();
            this.myList = new JList(this.listModel);
            this.myList.setBackground(Color.WHITE);
            this.myist.setForeground(Color.BLUE);
            this.myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            this.myList.setPreferredSize(getPreferredSize());
            this.add(new JScrollPane(this.myList));
            TitledBorder border = new TitledBorder("List"));
            border.setTitleColor(Color.BLUE);
            border.setTitleJustification(TitledBorder.CENTER);
            this.setBorder(border);
            this.setVisible(true);
        }

    Thanks, using the borderlayout the panel now shows fine to me. However I removed the setPreferredSize line in order not ot have the jlist to use scrollbars even if empty.
    By the way, can you explain why the FlowLayout did not work and the border layout did it?
    Thanks.

  • How to prevent a JPanel to grow ?

    Hello,
    I've included a JPanel in a JScrollPane.
    When I size down the whole thing, scroll bars appear. Nice.
    But when I size up, the JPanel grows and its content (buttons) is stretched.
    I would like the JPanel to always keep the same size, and some grey area to appear around it when the JScrollPane is sized up. I've tried with :
    panel.setMaximumSize (panel.getPreferredSize ());
    panel.setMinimumSize (panel.getPreferredSize ());
    But it does nothing...
    Do you know how to do ?
    Matthieu

    Subclass the JPanel and return your own fixed preferredSize always.

  • JPanel formatting

    After succesfully coding a couple of panels to show correctly in my frame, I continued to develop the menu until the formatting for one of my menus reset itself. I'm not sure what happened, and if I message out the things I've changed it still doesn't format correctly. Basically the menu consists of a frame, with each menu as a smaller sized panel in the middle of the frame. The EquipPanel now resizes itself to take over the entire frame, rather than just be a smaller box inside the frame. Any help would be great, if you can spot the code or even suggest another plan of attack to build the menu. Here's the code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class NecMenu implements ActionListener
        Font            f;
        Font            f2;
        Dimension       maxSize;
        Container       c;
        JLabel          title;
        JLabel          sign;
        JPanel          currentPanel;
        JPanel          mainPanel;
        JPanel          equipPanel;
        JPanel          gangPanel;   
        JButton         viewGangs;
        JButton         viewEquip;
        JButton         viewMain;
        JFrame          frame;
        int             titwid;
        public NecMenu()
            mainPanel   = new MainPanel();
            equipPanel  = new EquipPanel();
            gangPanel   = new GangPanel();
            title       = new JLabel( "Title", JLabel.CENTER );
            f           = new Font( "Lucida Sans", 1, 30 );
            viewGangs   = new JButton( "View Gangs" );
            viewEquip   = new JButton( "View Equipment" );
            viewMain    = new JButton( "Main Menu" );
            sign        = new JLabel( "Signature" );
            f2          = new Font( "Lucida Sans", 2, 14 );
            title.setFont( f );       
            sign.setFont( f2 );
            runMenu();
        void addComponentsToPane(Container pane)
            Dimension size = title.getPreferredSize();
            currentPanel = mainPanel;
            pane.add( title );
            pane.add( sign );
            pane.add( viewMain );
            mainPanel.setBorder( new LineBorder( Color.black, 3 ) );
            mainPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
            equipPanel.setBorder( new LineBorder( Color.black, 3 ) );
            equipPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
            gangPanel.setBorder( new LineBorder( Color.black, 3 ) );
            gangPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
            pane.add( mainPanel );
            pane.add( gangPanel );
            pane.add( equipPanel );
            gangPanel.setVisible( false );
            equipPanel.setVisible( false );
            title.setBounds( ( frame.getWidth() - size.width ) / 2, 5, size.width, size.height );
            size = sign.getPreferredSize();
            sign.setBounds( 780 - size.width, 540, size.width, size.height );
            viewGangs.setBounds( 250, 200, 300, 30 );
            viewEquip.setBounds( 250, 300, 300, 30 );
            viewMain.setBounds( 250, 538, 300, 28 );
            viewGangs.addActionListener( this );
            viewEquip.addActionListener( this );
            viewMain.addActionListener( this );
            mainPanel.add( viewGangs );
            mainPanel.add( viewEquip );
        void createAndShowGUI()
            frame = new JFrame( "Nec" );
            frame.setSize( 800, 600 );
            JFrame.setDefaultLookAndFeelDecorated( true );
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            addComponentsToPane( frame.getContentPane() );
            frame.setVisible( true );
        void runMenu()
            javax.swing.SwingUtilities.invokeLater( new Runnable()
                public void run()
                    createAndShowGUI();
        public void actionPerformed( ActionEvent a )
            Object source = a.getSource();
            if ( source == viewGangs )
                changePanel( gangPanel );
            else if ( source == viewEquip )
                changePanel( equipPanel );
            else if ( source == viewMain )
                changePanel( mainPanel );
        void changePanel( JPanel panel )
            currentPanel.setVisible( false );
            panel.setVisible( true );
            currentPanel = panel;
    }and EquipPanel
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JComponent.*;
    public class EquipPanel extends JPanel implements ChangeListener, ActionListener
        EquipPanel[]    tabs;
        String[]        tabNames;
        JTabbedPane     pane;
        Font            f;
       EquipPanel()
            int i;
            tabs        = new EquipPanel[ Equipment.types.size() ];
            tabNames    = new String[ Equipment.types.size() ];
            pane        = new JTabbedPane( JTabbedPane.TOP );
            f           = new Font( "Lucida Sans", 0, 14 );
            for ( i = 0; i < Equipment.types.size(); i++ )
                tabNames[ i ]   = Equipment.types.get( i ).toString();
                tabs[ i ]       = new EquipPanel( tabNames[ i ], this );
                pane.add( tabNames[ i], tabs[ i ] );
                pane.addChangeListener( tabs[ i ] );
            this.add( pane );
            this.setBounds( 400,200,500,300);
        EquipPanel( String name, EquipPanel main )
            ArrayList arr   = Equipment.determineArray( name );
            JButton[] buttons = new JButton[ arr.size() ];
            for ( int i = 0; i < arr.size() - 1; i++ )
                buttons[ i ] = new JButton( arr.get( i + 1 ).toString() );
                add( buttons[ i ] );
                buttons[ i ].addActionListener( main );
        public void stateChanged( ChangeEvent ce )
        public void actionPerformed( ActionEvent ae )
            String source =( ( JButton ) ae.getSource() ).getText();
    }and MainPanel if you wanted to see it in action
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class MainPanel extends JPanel
        public MainPanel()
            setName( "Main" );
    }Thanks guys

    Read this section from the Swing tutorial on "Using Layout Managers":
    http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
    Absolute Positioning is what you want.

  • Centering a Jpanel on screen

    Hi.
    I'd like to center my JPanel to the center of the screen.
    I've looked around, however i can't find out how to do it.
    I found about setting the "bounds", however that is based on x, y Co-ordinates, and i'd like it to be centered for people on 800 x 600 resolutions, as well as 1024 x 768 (for example).
    The other way i found is by:
    Login.setVerticalAlignment(JFrame.CENTER);However that results in an error during compilation:
    Compiling 1 source file to W:\Java\Covenant\build\classes
    W:\Java\Covenant\src\covenant\Login.java:81: cannot find symbol
    symbol  : variable CENTER
    location: class javax.swing.JFrame
            Login.setHorizontalAlignment(JFrame.CENTER);
    W:\Java\Covenant\src\covenant\Login.java:82: cannot find symbol
    symbol  : variable CENTER
    location: class javax.swing.JFrame
            Login.setVerticalAlignment(JFrame.CENTER);
    2 errors
    BUILD FAILED (total time: 0 seconds)So my question is, how can i do it?
    Thanks for any help.

    I havn't got another setLocation() or setBounds() in my code, and i havn't sized my frame.
    The code is:
        public Login() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            Title = new javax.swing.JLabel();
            Username = new javax.swing.JTextField();
            UsernameLabel = new javax.swing.JLabel();
            PasswordLabel = new javax.swing.JLabel();
            Password = new javax.swing.JPasswordField();
            LoginButton = new javax.swing.JButton();
            FooterText = new javax.swing.JLabel();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Login");
            setBounds(new java.awt.Rectangle(0, 0, 0, 0));
            setLocationRelativeTo(null);
            setResizable(false);
            Title.setFont(new java.awt.Font("Tahoma", 1, 12));
            Title.setText("The Covenant Farm Program");
            Username.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    UsernameActionPerformed(evt);
            UsernameLabel.setText("Username:");
            PasswordLabel.setText("Password:");
            LoginButton.setText("Login");
            LoginButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    logincheck(evt);
            FooterText.setText("You must be a Covenant Member to use this Program");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(65, 65, 65)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(UsernameLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(Username, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(PasswordLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(LoginButton)
                                        .addComponent(Password, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addComponent(FooterText))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(57, 57, 57)
                            .addComponent(Title)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(Title, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(17, 17, 17)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(UsernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(Username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(Password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(PasswordLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(14, 14, 14)
                    .addComponent(LoginButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(FooterText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }Thanks for the help :)

  • JPanel not extending to full size of JFrame

    Hello,
    I have a JFrame that represents the launch of my application. The frame is sized for a Welcome message and a subsequent login. Once login has occurred, I have resized the JFrame to fit the application. The frame resizes, but the panels within the frame do not change. I am using revalidate() to update the panel, which works fine for the contents, but, again, the size of the panel if the original size of the panel from the previous frame size. I am at a loss at this point as to how I get past this issue.

    I don't understand what you mean? Also, when I use pack(), my login button, which should appear as south in pane1, appears next to my label in the west.
    Here is some code:
    private JFrame frame = new JFrame();
    private JPanel panel = new JPanel();
    ERPLaunch2()
         // Setup Application Frame
         super("The New Unison ERP System");
         setBounds(280,220,500, 350);
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         // Setup Application Panel
         panel.setLayout(new BorderLayout());
         // Setup Application Pane 1
         pane1.add(cpane1, BorderLayout.CENTER);
         pane1.add(spane1, BorderLayout.SOUTH);
         cpane1.setLayout(new FlowLayout());
         spane1.setLayout(new FlowLayout());
         cpane1.add(welcomelbl);
         spane1.add(loginbtn);
         // Setup Application Pane 2
         pane2.add(cpane2);
         pane2.add(spane2);
         cpane2.setLayout(new BorderLayout());
         cpane2.add(gpane2, BorderLayout.CENTER);
         spane2.setLayout(new BorderLayout());
         spane2.add(fpane2, BorderLayout.SOUTH);
         gpane2.setLayout(new GridLayout(2,2));
         gpane2.add(new JLabel("<html>User Name: <P>"));
         gpane2.add(uname);
         gpane2.add(new JLabel("<html><P>Password: "));
         gpane2.add(upasswd);
         fpane2.add(okbtn);
         fpane2.add(cancelbtn);
         // Setup Application Pane 3
         pane3.setLayout(new BorderLayout());
         pane3.add(tpane3, BorderLayout.NORTH);
         pane3.add(cpane3, BorderLayout.CENTER);
         pane3.add(bpane3, BorderLayout.SOUTH);
         cpane3.add(sppane3);
         sppane3.setLayout(new GridLayout(1,1));
         tpane3.setLayout(new FlowLayout(FlowLayout.RIGHT));
         sppane3.add(rpane3, BorderLayout.CENTER);
         tpane3.add(logoutbtn);
         bpane3.add(label3);
         rpane3.add(tbpane3);
         // Populate tbpane3 in rpane3 of pane 3
         populateTabbedPane();                    
         // Setup Default Panel as Pane 1 and add to Frame
         panel.add(statusBar, BorderLayout.SOUTH);
         panel.add(pane1);
         getContentPane().add(panel);
         loginbtn.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
              panel.remove(pane1);
              panel.add(pane2);
              panel.revalidate();
         okbtn.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
              //setBounds(280,220,500, 350);
              setSize(500,350);
              frame.pack();
              frame.show();
              //panel.repaint();
              panel.remove(pane2);
              panel.add(pane3);
              panel.repaint();
              panel.revalidate();
         cancelbtn.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
              System.exit(0);
         logoutbtn.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
              System.exit(0);
    public static void main(String args[])
         ERPLaunch2 frame = new ERPLaunch2();
         frame.setSize(275,350);
         frame.pack();
         frame.show();
    }

  • Making a customable resizable JPanel, but it only works in certain L&F

    Hi,
    I have created the following resizable JPanel (so that I can set a minimum size it can be dragged to).
    However, I need it to work under the system L&F, which is XP, but it wont work.
    The code is below. if you run it the first time, and try to resize the dialog to a small value, you will see it shrinks in size, to a certain point.
    then if you comment out the 2 lines i specified, and run it again, it wont. Anyone have any ideas? is this a known bug?
    import javax.swing.*;
    import java.awt.event.ComponentListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.*;
    public class ResizeTest extends JDialog {
         public ResizeTest(JFrame owner) {
              super(owner);
              this.addComponentListener(resizeListener);
              /* comment out the following 2 lines */
              setUndecorated(true);                  
            getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
         private ComponentListener resizeListener = new ComponentListener() {
              public void componentHidden( ComponentEvent i_e ) { }
              public void componentMoved( ComponentEvent i_e ) { }
              public void componentResized( ComponentEvent i_e ) {
                   int width = ResizeTest.this.getWidth();
                   int height = ResizeTest.this.getHeight();   
                  if( width < 50 ) { width = 50; }
                   if( height < 50 ) { height = 50; }
                   ResizeTest.this.setSize( width, height );
             public void componentShown( ComponentEvent i_e ) { }
         private static void test() {
              final JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JButton launchButton = new JButton("showDialog");
              frame.setContentPane(launchButton);
              final ResizeTest testDialog = new ResizeTest(frame);
              testDialog.setMinimumSize(new Dimension(300, 300));
              testDialog.setSize(500, 500);
              testDialog.setPreferredSize(new Dimension(500, 500));
              launchButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        testDialog.pack();
                        testDialog.setVisible(true);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.setVisible(true);
         public static void main(String[] args) {
              test();
    }

    okay... I see what the problem is.
    1) With those lines uncommented: The L&F is handling the window decorations. Because of this, it's basically a JWindow with custom painting and mouse handling. When you resize, it's constantly calling setSize, which constantly firing events, so your minimum sizing works as you expect.
    2) With those lines commented: The OS is handling the window decorations. Because of this, there are 2 caveats:
    a) There is a minimum width of the window of what looks like about 120-130 pixels. So you can't go any smaller then that for width. And for height, no smaller then the titlebar and lower border.
    b) It only fires the component events when the mouse is released, cuz that's how the undelying native windows deal with it... or at least with Java.
    For #1 above, there's still a minimum size for the L&F decorated windows. But this is related to what content is showing in the titlebar. Which in the case of the decorations showing, is smaller then what your were defining as a minimum.
    So, basically, it's not a bug. It's just the way it is. It's always been like this.

Maybe you are looking for