Nested JPanel resizing

In one of my application there is one Jframe( BorderLayout) containing panel at the center surrounded with JScrollPane. The panel contains one more JPanel in it.
On click of a button i need to resize both the panel.
in the event handler method, Im caling setPreferedSize() and setSize() for both the panels.
Only outer panel gets resized for the first click and for the second click inner panel gets resized...
how can i solve this problem...?

There is no way of knowing where the problem is without the code, however, you said you have called the setPreferedSize() and setSize() methods in the event handler.
This should get called when you press the button, one thing you must do is to make sure that they are both inside the same block of code. If you are using an if statement.
if(buttonPressed()){
setPreferedSize();
setSize();
}Or you could post a simple version to help us solve the problem.

Similar Messages

  • Dynamic JPanel resizing?

    Hey all,
    I'm displaying an image in a JPanel and I want the user to be able to resize the panel by dragging with the mouse as you would say in Photoshop. Obviously the image should resize to fill the panel as it's enlarged (showing resizing handles on the image/panel would also be good).
    For bonus points:
    I also have a draggable method so the image can be moved on the screen, the resizing method should only be applied when the mouse is over the edges of the image/panel.
    Thanks for your suggestions.

    For bonus points:
    I also have a draggable method so the image can be moved on Ooh bonus points! Now ur talking
    Search google for my Resizeable.java class. This should take care of resizing. As far as scaling the image, that call all be done in the paintComponent method. But actually I've got a class for this too
    You are welcome to use and modify this class, but please don't change the package or take credit for it as your own work (except where you have modified it)
    ExpandableImagePanel.java
    ======================
    package tjacobs.ui.ex;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;
    import javax.swing.JPanel;
    import tjacobs.ui.fc.FileExtensionFilter;
    import tjacobs.ui.swing_ex.JFileChooser;
    import tjacobs.ui.util.WindowUtilities;
    * @deprecated use BackgroundImagePanel
    * @see BackgroundImagePanel
    * @author HP_Administrator
    public class ExpandableImagePanel extends JPanel {
         private static final long serialVersionUID = 1L;
         Image mOriginal;
         public ExpandableImagePanel() {
         public ExpandableImagePanel(Image im) {
              this();
              setImage(im);
         public ExpandableImagePanel(LayoutManager arg0) {
              super(arg0);
         public ExpandableImagePanel(boolean arg0) {
              super(arg0);
         public ExpandableImagePanel(LayoutManager arg0, boolean arg1) {
              super(arg0, arg1);
         public void setImage(Image im) {
              mOriginal = im;
         public Image getImage() {
              return mOriginal;
         public void paintComponent(Graphics g) {
              //super.paintComponent(g);
              g.clearRect(0, 0, getWidth(), getHeight());
              g.drawImage(mOriginal, 0, 0, getWidth(), getHeight(), null);
         public static void main(String[] args) {
              JFileChooser chooser = new JFileChooser();
              chooser.addChoosableFileFilter(new FileExtensionFilter.ImageFilter());
              int approve = chooser.showOpenDialog(null);
              if (approve == javax.swing.JFileChooser.APPROVE_OPTION) {
                   //BufferedImage im = new BufferedImage(chooser.getSelectedFile());
                   Image im = Toolkit.getDefaultToolkit().createImage(chooser.getSelectedFile().getAbsolutePath());
                   ExpandableImagePanel p = new ExpandableImagePanel(im);
                   p.setPreferredSize(new Dimension(300,300));
                   WindowUtilities.visualize(p);
    }

  • Weird JPanel Resizing Problem

    This program works as I want it to with one exception: sometimes when resizing the frame, the contained JPanels do not fully cover the frame's BorderLayout center region. If you run the program you'll discover that a light gray area often appears on the right and bottom edges of the frame when it's resized. Any ideas? Thanks. I'm using version 1.3.1._01 on Windows 98.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Grid extends JPanel implements ComponentListener
    private int rows, columns;
    private Block[][] block;
    public Grid()
    rows = 20;
    columns = 10;
    block = new Block[rows][columns];
    setLayout(new GridLayout(rows,columns,0,0));
    for (int i = 0; i < rows; i++)
    for (int j = 0; j < columns; j++)
    block[j] = new Block();
    if ((i % 4) >= 1)
    block[j].turnOn();
    else
    block[j].turnOff();
    add(block[j]);
    }//end inner for loop
    }//end outer for loop
    setBorder(BorderFactory.createLineBorder(Color.black,4));
    addComponentListener(this);
    }//end default constructor
    public Dimension getPreferredSize()
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    return new Dimension((block[0][0].getBlockWidth() * columns) + horizontalInsets,
    (block[0][0].getBlockHeight() * rows) + verticalInsets);
    }//end getPreferredSize
    public void componentHidden(ComponentEvent ce)
    //Invoked when the component has been made invisible.
    public void componentMoved(ComponentEvent ce)
    //Invoked when the component's position changes.
    public void componentResized(ComponentEvent ce)
    //Invoked when the component's size changes.
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    setPreferredSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
    setMinimumSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
    public void componentShown(ComponentEvent ce)
    //Invoked when the component has been made visible.
    public static void main(String[] args)
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Grid(),BorderLayout.CENTER);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Block extends JPanel implements ComponentListener
    private int blockWidth, blockHeight;
    private Color blockBackgroundColor, blockBorderColor, onColor;
    private String blockOwner;
    private boolean isOn;
    public Block()
    blockWidth = 20;
    blockHeight = 20;
    //setSize(20,20);
    //setPreferredSize(new Dimension(20,20));
    blockBackgroundColor = Color.gray;
    blockBorderColor = Color.black;
    setLayout(new BorderLayout(0,0));
    setBorder(BorderFactory.createLineBorder(blockBorderColor,1));
    setBackground(blockBackgroundColor);
    isOn = false;
    blockOwner = "1";
    onColor = Color.orange;
    addComponentListener(this);
    setVisible(true);
    }//end default constructor
    public Block(int blockWidth, int blockHeight)
    this();
    this.blockWidth = blockWidth;
    this.blockHeight = blockHeight;
    }//end two-arg constructor
    public void setBlockWidth(int blockWidth)
    this.blockWidth = blockWidth;
    public int getBlockWidth()
    return blockWidth;
    public void setBlockHeight(int blockHeight)
    this.blockHeight = blockHeight;
    public int getBlockHeight()
    return blockHeight;
    public void setBlockBorderColor(Color blockBorderColor)
    this.blockBorderColor = blockBorderColor;
    public Color getBlockBorderColor()
    return blockBorderColor;
    public void setBlockBackgroundColor(Color blockBackgroundColor)
    this.blockBackgroundColor = blockBackgroundColor;
    public Color getBlockBackgroundColor()
    return blockBackgroundColor;
    public void setOnColor(Color onColor)
    this.onColor = onColor;
    public Color getOnColor()
    return onColor;
    public void turnOn()
    setBackground(onColor);
    isOn = true;
    public void turnOff()
    setBackground(blockBackgroundColor);
    isOn = false;
    public void setBlockOwner(String blockOwner)
    this.blockOwner = blockOwner;
    public String getBlockOwner()
    return blockOwner;
    public Dimension getPreferredSize()
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    return new Dimension(blockWidth + horizontalInsets,
    blockHeight + verticalInsets);
    }//end getPreferredSize
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    if (isOn)
    FontMetrics fm = g.getFontMetrics();
    int blockOwnerWidth = fm.stringWidth(blockOwner);
    int blockOwnerAscent = fm.getAscent();
    int x = (blockWidth / 2) - (blockOwnerWidth / 2);
    int y = (blockHeight / 2) + (blockOwnerAscent / 2);
    g.drawString(blockOwner,x,y);
    }//end paintComponent
    public void componentHidden(ComponentEvent ce)
    //Invoked when the component has been made invisible.
    public void componentMoved(ComponentEvent ce)
    //Invoked when the component's position changes.
    public void componentResized(ComponentEvent ce)
    //Invoked when the component's size changes.
    int horizontalInsets = getInsets().left + getInsets().right;
    int verticalInsets = getInsets().top + getInsets().bottom;
    blockWidth = this.getWidth();
    blockHeight = this.getHeight();
    setPreferredSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
    setMinimumSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
    public void componentShown(ComponentEvent ce)
    //Invoked when the component has been made visible.

    Your problem is due to the use of a GridLayout.
    With a GridLayout, all components must have the same dimension. And the extra space has to be divisible by the number of components to be distributed to each component :
    For example : In a component with a GridLayout, you have a line with 10 JPanels. The width of the component is initially 100. In this case, each JPanel will have a width of 10 (10*10=100).
    If you resize the main component to a width of 110, each JPanel will have a size of 11 (11*10=110).
    But in the case where the width is not divisible by the number of JPanels, there will be an extra-space :
    if the width of the component is 109, the width of each JPanel will be 10 and there will be an extra-space of 9 (10*10+9 = 109).
    I hope this helps,
    Denis

  • JSplitPane, JScrollPane, JPanel & resize

    My program has 2 nested JSplitpanes, that divide the screen in 4 parts like a cross.
    I added a JScrollPane to one of the quaters and added a JPanel to the JScrollPane. The JPanel uses a CardLayout since I want to switch the components that I show there.
    One of the components I show on the JPanel is a JTree. If I expand the tree the panel becomes scrollable to show the whole tree. This is what I want because I want to be able to view the whole tree.
    The problem is, that if I switch to another component on the panel the panel stays that large even though I just want it to have the visible size
    This is how the panel looks like before switching to the tree and expanding it:
    http://img272.imageshack.us/img272/8695/noscroll3zj.jpg
    This is how the panel looks like after switching to the tree, expanding it and switching back:
    http://img272.imageshack.us/img272/6690/scroll3ef.jpg
    I want to restore the panel to its initial state but I cannot figure out how. Please help.

    If I add a panel to the split pane (to make it card layout) I can't use it for scrolling anymoreThis simple example works for me:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SplitPaneCard extends JFrame
         JSplitPane splitPane;
         JPanel cards;
         public SplitPaneCard()
              splitPane = new JSplitPane();
              getContentPane().add(splitPane, BorderLayout.CENTER);
              JTextArea textArea1 = new JTextArea(5, 10);
              textArea1.setText("1\n2\n3\n4\n5\n6\n7");
              textArea1.setForeground( Color.RED );
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              JTextArea textArea2 = new JTextArea(5, 10);
              textArea2.setText("1234567");
              textArea2.setForeground( Color.BLUE );
              JScrollPane scrollPane2 = new JScrollPane( textArea2 );
            cards = new JPanel( new CardLayout() );
            cards.add(scrollPane1, "red");
            cards.add(scrollPane2, "blue");
            splitPane.setRightComponent( cards );
              JPanel buttonPanel = new JPanel();
              getContentPane().add(buttonPanel, BorderLayout.SOUTH);
              JButton red = new JButton("Show Red Text Area");
              red.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "red");
              buttonPanel.add(red);
              JButton blue = new JButton("Show Blue Text Area");
              blue.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "blue");
              buttonPanel.add(blue);
         public static void main(String[] args)
              final SplitPaneCard frame = new SplitPaneCard();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Jpanel, resize, borderlayout, browser, applet

    Sorry i cant find a good topic for my problem. :) I have an applet with a borderlayout, each time the browser is resize, my applet component is resize too , its ok, BUT i need to put a maximum size for my JPanel (in "Center"), is there a way to change the way that the automatic resize works? I explain why, i have a JPanel, the center one, that have a picture draw on it, when the view area of the JPanel is tiner than the size of the image, i put scrollbar, but i dont want to have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to explain in english, it could be not understandable :)
    thx a lot in advance

    try this, maybe works as you want,
    here component is you JPanel;
    Component component = new Component(){
    public Dimensin getMaximumSize()
    return new Dimension( 100, 100 ); // your picture size
    and as this you can overwrite
    getMinimumSize() and getPreferredSize() methods,
    Sorry i cant find a good topic for my problem. :) I
    have an applet with a borderlayout, each time the
    browser is resize, my applet component is resize too ,
    its ok, BUT i need to put a maximum size for my JPanel
    (in "Center"), is there a way to change the way that
    the automatic resize works? I explain why, i have a
    JPanel, the center one, that have a picture draw on
    it, when the view area of the JPanel is tiner than the
    size of the image, i put scrollbar, but i dont want to
    have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to
    explain in english, it could be not understandable :)
    thx a lot in advance

  • Nested JPanels

    For a game GUI I have made each square of the board as a JPanel and these are all nested inside another JPanel which represents the whole gameboard. Can anyone tell me how (if possible) f.ex. each square can catch it's own MouseReleased event? The parent JPanel(the gameboard) seems to catch all MouseEvents.

    hi,
    i am not sure if i understood ur problem rigth, but i think u have a panel within a apnel right? if so, then just write the action listeners for teh sub-panels the same way u wrote for the main panel and it shud work fine.....let me know if it works..........sorry if it is a silly answer

  • Accessing a nested JPanel

    The format:
    JFrame that contains 2 JPanels that I want to switch depending on user input.
    I've tried from with the JFrame code:
    JPanel jpanel1 = new JPanel();
    The constructor in JPanel1 creates an instance of jPanel2 & jPanel3.
    jPanel1.jPanel2.setVisible(true);
    jPanel1.jPanel3.setVisible(false);
    This doesn't work - any ideas on how to accomplish the task?
    Thanks,
    Michael

    What jdbc driver and database version are you on? What happens if you do not cast to Status? Does it return a STRUCT? What is the stack trace?
    The following seems to work:
    create or replace type status_typ is object(
    attribute1 varchar2(50),
    attribute2 varchar2(50),
    attribute3 varchar2(50)
    create or replace type status_tab is table of status_typ
    create or replace procedure get_status(
      s out status_tab
    ) is
    begin
    s := status_tab(status_typ('a','b','c'));
    end;
    show errors
      // Status.java
      public class Status implements SQLData {
        protected String
          attribute1, attribute2, attribute3, sql_type;
        public String getSQLTypeName() {
          return sql_type;
        public void readSQL(SQLInput stream, String typeName) throws SQLException {
          sql_type = typeName;
          attribute1 = stream.readString();
          attribute2 = stream.readString();
          attribute3 = stream.readString();
        public void writeSQL(SQLOutput stream) {
        OracleCallableStatement cs = (OracleCallableStatement)conn.prepareCall(
        "{call get_status(?)}"
        cs.registerOutParameter(1, OracleTypes.ARRAY, "STATUS_TAB");
        cs.execute();
        Map map = conn.getTypeMap();
        map.put("STATUS_TYP",Class.forName("Status"));
        int i = 0;
        ResultSet rs = cs.getArray(1).getResultSet();
        while(rs.next()) {
          Status s = (Status)rs.getObject(2);
          System.out.println("Row " + i++ + " " + rs.getObject(2) + " " + s.attribute1 + "," + s.attribute2 + "," + s.attribute3);
    Row 0 Status@b01d43 a,b,c

  • Question on program structure about event handling in nested JPanels in GUI

    Hi All,
    I'm currently writing a GUI app with a wizard included in the app. I have one class that acts as a template for each of the panels in the wizard. That class contains a JPanel called contentsPanel that I intend to put the specific contents into. I also want the panel contents to be modular so I have a couple of classes for different things, e.g. name and address panel, etc. these panels will contain checkboxes and the like that I want to event listeneres to watch out for. Whats the best way of implementing event handling for panel within panel structure? E.g for the the checkbox example,would it be a good idea to have an accessor method that returns the check book object from the innerclass/panel and use an addListener() method on the returned object in the top level class/panel. Or is it better to have the event listeners for those objects in the same class? I would appreciate some insight into this?
    Regards!

    MyMainClass.main(new String[] { "the", "arguments" });
    // or, if you defined your main to use varags (i.e. as "public static void main(String... args)") then you can just use
    MyMainClass.main("the", "arguments");But you should really extract your functionality out of the main method into meaningful classes and methods and just use those from both your console code and your GUI code.

  • JPanel Resizes Self

    This is from fairly large code so I'm trying to pull the important stuff out of two classes:
    MainM.class:
        private void bPlayActionPerformed(java.awt.event.ActionEvent evt) {
            game=new Game(WD+"\\songs\\"+cmbSong.getSelectedItem(),this,settings.FPS,getWidth(),getHeight());
            JPMain.setVisible(false);
            java.awt.GridBagConstraints gc=new java.awt.GridBagConstraints();
            gc.gridx=0;gc.gridy=0;
            getContentPane().add(game,gc);
            game.animator.start();
        }Game.class:
        public Game(String SongFile, MainM JMain, int iFPS, int Width, int Height) {
            addKeyListener(this);
            setVisible(true);
            setMinimumSize(new Dimension(Width,Height));
            setSize(Width,Height);
            animator=new Thread(this);
        public void run() {
            // Remember the starting time
            long tm = System.currentTimeMillis();
            while (Thread.currentThread() == animator) {
                // Display the next frame of animation.
                manpaint();
                // Delay depending on how far we are behind.
                try {
                    tm += 1000/FPS;
                    Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
                } catch (InterruptedException e) {
                    break;
                // Advance the frame
                CurBeat+=BPF;
        public void manpaint() {
            Graphics g=getGraphics();
            int x,y,xunit,yunit,dx,dy;
            xunit=getWidth()/ScaleX;
            yunit=getHeight()/ScaleY;
            // Now draw the image scaled.
            System.out.println(getWidth());
            g.drawImage(Pics[0],0,0,getWidth(),getHeight(),this);
            g.drawImage(Pics[1],ScaleX*(CurTrack*(ScaleX/10)),yunit*(ScaleY-7),yunit*10,yunit*4,this);
            for(x=0;x<Tracks.length;x++){
                for(y=0;y<Tracks[x].CurBeats.length;y++){
                    if (Tracks[x].CurBeats[y][0]!=-1){
                        dx=xunit*(x*(ScaleX/Tracks.length))+xunit*x+xunit*3*Tracks[x].CurBeats[y][1];
                        dy=yunit*y+yunit*(-2)+(int)(yunit*(CurBeat-(int)CurBeat));
                        g.drawImage(Pics[2],dx,dy,xunit*2,yunit*2,this);
            update(g);
        }And the problem is:
    In this last method there is a line "System.println.(getwidth());" for the first time it prints 400, the correct width, but after the first print it starts printing 10's, so in accordance, on the screen it draws the first frame correctly and then refreshes a tiny fram in the center of the screen 10 pixels wide and tall. There is no code to resize this panel other than when it is initialized, is there any reason it should be resizing itself?

    solved the resizing problem, have to set preferred size instead of just using setsize (for the record)

  • Auto-resizing JPanel  on mouseEntered

    Hello,
    I am looking for a little advice. I want to try and make a JPanel resize on mouseEntered. I want the JPanel to be be almost hidden until the mouse is over and I want it to grow in size gradually rather than appear instantly. The Panel will share space with a JEditorpane which will occupy the majority of the space but resize to allow to the JPanel to grow in size.
    --Hidden
    ///////////////////////////////////////////////////////////////////////////////////// - Base panel
    ////////////////////////////////////////////////////////////////////////////////////// - JPanel almost hidden
    /                               JEditorPane                                             /
    ////////////////////////////////////////////////////////////////////////////////////// - Base panel
    --On Mouse Over
    /////////////////////////////////////////////////////////////////////////////////////// - Base panel
    /                          JPanel now showing                                 /
    /                         JEditorPane                                                  /
    //////////////////////////////////////////////////////////////////////////////////////// - Base panelThe JPanel will start of with a height of say 5 and when the mousentered event is fired it will grow over the space of half a second or so to a height of about 80. When the Mouse exists I want to to go back to it's original position.
    I have seen this technique used on some desktop applications I have used in the past and I would like some advice on how best to accomplish this in Swing.
    Has anyone done this before, or if not which way might it be possible?
    I am not expecting code, just some ideas on an approach. I am not really that good when it comes to Swing.
    BTW, I have tried already with a JPanel as the base panel and a JLayeredPane but the JPanel I wish to resize ignore the calls to setSize, possible becuase it has various components embedded on to it.
    Cheers.

    BTW, I have tried already with a JPanel as the base panel and a JLayeredPane but the JPanel I wish to resize ignore the calls to setSize, possible becuase it has various components embedded on to it. When using JLayeredPane, the trick would be to use setBounds( ) instead.
    Basically to achieve this you would need a simple javax.swing.Timer and the necessary MouseListeners. Consider creating a subclass of JPanel where you will attach the listener code. Once, the mouseEnters, you'll probably need to set a boolean which indicates that the panel should grow, and fire the Timer. The Timer's actionPerformed method should check the boolean to determine whether to grow the panel or shrink it. The changes to the panel should be done through setPreferredSize( ).
    Consider removing all the items in the Panel before shrinking and re-adding them only when the Panel is fully grown. This may help improve performance.
    This feature may cause your application to suffer a bit in terms of appearance when the panel growing or shrinking unless a suitable LayoutManager is choosen. Cant suggest any unless I try it my self.
    ICE

  • Resizing windows and components

    Hi, i've been reading the swing tutorial on springLayout but i still haven't figured out how to do it.
    Basically I want a jTable in a jScrollPane to resize itself whenever i resize the window. The window would also have other buttons, which positions I want to stay relatively constant to the borders (ex: always in the middle, or always to the left, etc. etc.), however i do not want to resize them. any ideas?
    Thnx
    Rickszyr

    Don't use SpringLayout. Assuming what you stated is all you want in the window, my suggestion is to do the following:
    1. The main window's content pane uses BorderLayout. Stick the JScrollPane containing the JTable in BorderLayout.CENTER.
    2. Create a second JPanel that will contain your buttons. Add this JPanel to your content pane wherever you want (e.g. BorderLayout.RIGHT if you want it to the right of the JTable, BorderLayout.SOUTH if you want them below, etc.). The LayoutManager you use for this second JPanel depends on how you want the buttons arranged.
    Basically, don't be afraid to nest JPanels with different LayoutManagers to achieve the layout you want. You'd be amazed with how much you can accomplish with BorderLayout and GridLayout, and sometimes a little bit of BoxLayout.

  • Make text areas and textfields streach as window resizes

    im using the border layout for most of my panels. how do i make text areas and textfields stretch as the window resizes?

    Components placed in BorderLayout.CENTER will resize as the window resizes.
    You will likely need to have nested JPanels, with different layouts, to create the ultimate layout of all your components in a frame, especially for non-trivial applications.
    If you need specific help with layouts, you'll have to post an SSCCE.

  • Need help placing objects in JPanel

          public SimpleTab()
                ButtonGroup group = new ButtonGroup();
                group.add(videoandaudio);
                group.add(audioonly);
                group.add(videoonly);
                videoandaudio.setSelected(true);    
                JFrame frame1 = new JFrame("project");
                frame1.setSize(1000, 700);
                JLabel urllabel = new JLabel("URL");
                JLabel songlabel = new JLabel ("Enter Song");
                JLabel artistlabel = new JLabel ("Enter Artist");
                JLabel crop1label = new JLabel ("Start Time");
                JLabel crop2label = new JLabel ("Stop Time");
                url.setColumns(25);
                GridBagLayout gbl;
                GridBagConstraints gbc;
                JEditorPane jep;
                gbl=new GridBagLayout();
                gbc=new GridBagConstraints();
                p.setBounds(0,0,30,600);
                p.setLayout(gbl);
                gbc.gridx=0;
                gbc.gridy=-20;
                gbl.setConstraints(urllabel,gbc);
                gbc.gridx=0;       
                gbc.gridy=0;
                gbc.weightx=0.0;
                gbl.setConstraints(urllabel,gbc);
                p.add(urllabel);
                gbc.gridx=10;
                gbc.gridy=0;
                gbc.weightx=1.0;
                gbl.setConstraints(url,gbc);
                p.add(url);
                gbc.gridx=0;
                gbc.gridy=20;
                gbc.weightx=0.0;
                gbl.setConstraints(artistlabel,gbc);
                p.add(artistlabel);
                gbc.gridx=10;
                gbc.gridy=20;
                gbc.weightx=1.0;
                gbl.setConstraints(artist,gbc);
                p.add(artist,gbc);
                gbc.gridx=0;
                gbc.gridy=40;
                gbc.weightx=0.0;
                gbl.setConstraints(songlabel,gbc);
                p.add(songlabel);
                gbc.gridx=10;
                gbc.gridy=40;
                gbc.weightx=0;
                gbl.setConstraints(song,gbc);
                p.add(song,gbc);
                gbc.gridx=0;
                gbc.gridy=60;
                gbc.weightx=0.0;       
                gbl.setConstraints(crop1label,gbc);
                p.add(crop1label,gbc);
                gbc.gridx=10;
                gbc.gridy=60;
                gbc.weightx=1.0; 
                gbl.setConstraints(crop1,gbc);
                p.add(crop1,gbc);
                gbc.gridx=0;
                gbc.gridy=80;
                gbc.weightx=0.0;
                gbl.setConstraints(crop2label,gbc);
                p.add(crop2label);
                gbc.gridx=10;
                gbc.gridy=80;
                gbc.weightx=1.0;
                gbl.setConstraints(crop2,gbc);
                p.add(crop2,gbc);
                gbc.gridx=0;
                gbc.gridy=110;
                gbc.weightx=0.0;
                jPanel1.setBorder(BorderFactory.createEtchedBorder());
                jPanel1.setBounds(new Rectangle(70, 40, 10, 200));
                gbc.gridy = 0;
                gbl.setConstraints(videoandaudio, gbc);
                jPanel1.add(videoandaudio);
                gbc.gridy = 20;
                gbl.setConstraints(audioonly, gbc);
                jPanel1.add(audioonly);
                gbc.gridy = 40;
                gbl.setConstraints(videoonly, gbc);
                jPanel1.add(videoonly);
                gbc.gridx = 0;
                gbc.gridy = 190;
                gbl.setConstraints(jPanel1, gbc);
                p.add(jPanel1);
                DownloadsTableModel1.addColumn("Video File");
                DownloadsTableModel1.addColumn("Status");
                DownloadsTable.getColumnModel().getColumn(0).setPreferredWidth(200);
                DownloadsTable.getColumnModel().getColumn(1).setPreferredWidth(200);
                DownloadsTable.setColumnSelectionAllowed(false);
                DownloadsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                DownloadsTable.setDefaultRenderer(Object.class, new DownloadsTableCellRenderer());
                JScrollPane jScrollPane1 = new JScrollPane();           
                jScrollPane1.setBounds(new Rectangle(10, 130, 400, 90));
                jScrollPane1.getViewport().add(DownloadsTable);
                gbc.gridx = 0;
                gbc.gridy = 210;
                gbl.setConstraints(jScrollPane1,gbc);
                p.add(jScrollPane1);
                gbc.gridx=1;
                gbc.gridy=230;
                gbc.weightx=0.0;
                JButton downloadbutton = new JButton();
                downloadbutton.setText("Download");
                gbl.setConstraints(downloadbutton,gbc);
                p.add(downloadbutton);
                JButton pausebutton = new JButton();
                pausebutton.setText("Freeze");
                gbc.gridx = 2;
                gbc.gridy = 230;
                gbl.setConstraints(pausebutton,gbc);
                p.add(pausebutton);
                JButton cancelbutton = new JButton();
                cancelbutton.setText("Cancel");
                gbc.gridx = 3;
                gbc.gridy = 230;
                gbl.setConstraints(cancelbutton, gbc);
                p.add(cancelbutton);
                frame1.add(p);
                frame1.show();
          }[http://www.geocities.com/justinknag/jjjjunit.jpg]
    I need to center the radio buttons, as well as the table. Also, I need to create some space in between everything.

    You know that you can nest JPanels, each with its own layout, you don't have to try to have everything placed in one JPanel that uses a single grand layout manager. I recommend that you read the Sun tutorial on layout managers, and try playing with them til you figure out what will work best. As it is all I see is an attempt to dump everything in one panel with GridBagLayout.
    Also, you would do well to clean up the code, to refactor it into several methods, otherwise it will become a spaghetti code mess.
    Good luck!
    Edit: Here's what I got when I did this:
    [flickr pic|http://farm4.static.flickr.com/3155/2906451640_8deedd7aa3_o.jpg]
    I used
    BoxLayout over-all for the main panel
    A combination of BorderLayout and GridLayout for the top panel
    gridlayout for the next radiobutton panel
    jscrollpane for the jtable
    and gridlayout for the buttons
    I avoided GridBagLayout, because I truly despise it.
    YMMV of course.
    Edited by: Encephalopathic on Oct 1, 2008 7:35 PM

  • JPanel inside a JFrame

    How do you make a JPanel resize automatically with its parent JFrame?
    Thanks,
    -Zom.

    Use BorderLayout for the JFrame and set the JPanel at centre like this:myJFrame.getContentPane().setLayout(new BorderLayout());
    myJFrame.getContentPane().add(myPanel,  JFrame.CENTER);

  • Scroll does not work in JPanel 's JScrollPane

    Hello,
    I have a JPanel and I am adding some components to this panel. The problem is that the Panel goes beyond the visible area of the monitor so some of the components cannot be seen. Therefore, I add a JScrollPane onto the panel.
    Some code:
    JScrollPane scroll_panel_inputs = new JScrollPane(panel_inputs);
    getContentPane().add(scroll_panel_inputs);       
    scroll_panel_inputs.validate();where "panel_inputs" is a JPanel.
    The problem is that despite adding too many components in the JPanel to be visible, I cannot scroll down , and the scroll bar doesn't change its length.

    A possible guess:
    1) If you don't specify a layout for the JPanel, it defaults to the FlowLayout.
    2) If you don't specify a preferred size of the JPanel (via setPreferredSize), it will extend itself to fit all of your components.
    So my guess is that your jpanel is extending way to the right to fit all the components one right after the other all on the same line, and that none of the components are being placed on the next line of the jpanel.
    If this is correct, a solution is to either set a preferred size of the panel so that the components will wrap to the next line when they run up against the right wall of the jpanel, or change the Layout manager for your jpanel. Even better would be to use several nested JPanels each with a different layout.
    For instance:
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    public class StuffedPanels extends JPanel
        public StuffedPanels()
            setLayout(new GridLayout(0, 1, 5, 5));
            setPreferredSize(new Dimension(1000, 800));
            JPanel panel1 = createStuffedPanel1();
            JPanel panel2 = createStuffedPanel1();
            // set only panel2's preferred size
            panel2.setPreferredSize(new Dimension(2000, 4000));
            JScrollPane stuffedScrollPane1 = new JScrollPane(panel1);
            JScrollPane stuffedScrollPane2 = new JScrollPane(panel2);
            stuffedScrollPane1.setBorder(BorderFactory.
                createTitledBorder("without setting preferred size"));
            stuffedScrollPane2.setBorder(BorderFactory.
                createTitledBorder("with setting preferred size"));
            add(stuffedScrollPane1);
            add(stuffedScrollPane2);
         * create a jpanel and stuff it with 1000 jlabels
         * @return the jpanel
        private JPanel createStuffedPanel1()
            JPanel stuffedPane = new JPanel();
            for (int i = 0; i < 1000; i++)
                JLabel label = new JLabel(" Hello Genius " + String.format("%4d", i));
                label.setFont(new Font(Font.MONOSPACED, Font.BOLD, 18));
                stuffedPane.add(label);
            return stuffedPane;
        private static void createAndShowGUI()
            JFrame frame = new JFrame("StuffedPanel Application");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new StuffedPanels());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

Maybe you are looking for

  • Mac mini with 2 - 500GB drives running X serve

    Hello - What is the best way to setup raid on a mac mini running 10.6.4x serve that does nothing but serve up netboot? Looking for suggestions.. Thanks

  • SQL 2012 installation Error-The MOF compiler could not connect with the WMI server

    Hi all,   I am getting below error while installing SQL 2012 Dev edition in Win 8.1 Pro. I am facing lot of issues while installing SQL 2012 in Win 8.1 Pro.Any other steps we need to take to install SQL 2012 in Win 8.1. Thanks in advance. 

  • Can't Connect To Skype Server

    Currently trying to connect to skype and I get stuck on signing in, and it attempts this for a while until it eventually will tell me skype can't connect. I have upgraded to the latest version of skype and I don't have an active firewall, can anyone

  • Installing New network card on a Cisco Catalyst 6500 VSS mode

    Hi All. I need to install a new network card on Cisco Catalyst 6500 VSS mode, I need to follow any special procedures or is it only insert the new card and the Catalyst automatically recognizes the card? Thank you So mucho. 

  • ISetup Configuration Question

    Hi Mugunthan Are iSetup configuration setups User specific. I did Instance Mapping, Create Extracts & Reports using my Apps Login I again login with different Login-id, i navigate to Oracle isetup, i dont see Instance mapping, extracts & reports. Can