How to make a JPanel containing buttons  take up the width of the window?

I'm creating a GUI and I have a button group that I want to be the width of the window. I have another JPanel on the same window that doesn't have a button group in it and it takes up the width of the window. I don't think I'm doing anything differently creating the two, but I need consistency.
The best way I can explain this is with code, so I created an example of what I am doing here:
import java.awt.*;
import javax.swing.*;
public class test extends JFrame {
     public test() {
          JPanel win = new JPanel();
          JPanel buttonsPanel = new JPanel();
          JPanel statusPanel = new JPanel();
          win.setLayout(new BoxLayout(win, BoxLayout.Y_AXIS));
          buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
          statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.Y_AXIS));
//          createRadioButtonsPanel
          ButtonGroup buttons = new ButtonGroup();
          JRadioButton currentMap = new JRadioButton("option1", true);
          JRadioButton newMap = new JRadioButton("option2");
          JRadioButton noMap = new JRadioButton("option3");
          buttons.add(currentMap);
          buttons.add(newMap);
          buttons.add(noMap);
          buttonsPanel.add(currentMap);
          buttonsPanel.add(newMap);
          buttonsPanel.add(noMap);
          buttonsPanel.setBorder(
                    BorderFactory.createTitledBorder("Create: "));
//           createStatusPanel
          JLabel statusLabel = new JLabel("Loading...");
          statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
          statusLabel.setPreferredSize(new Dimension(400,20));
          statusLabel.setMinimumSize(new Dimension(400,20));
          statusLabel.setMaximumSize(new Dimension(400,20));
          statusPanel.add(statusLabel);
          JPanel statusButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
          JButton pauseSearch = new JButton("Pause");
          JButton cancelSearch = new JButton("Cancel");
          statusButtons.add(pauseSearch);
          statusButtons.add(cancelSearch);
          statusPanel.add(statusButtons);
          statusPanel.setBorder(BorderFactory.createTitledBorder("Status: "));
          win.add(buttonsPanel);
          win.add(statusPanel);
          getContentPane().add(win);
          pack();
          setVisible(true);
     public static void main(String args[]) {
          test s = new test();
}When I compile and run this class I get this window:
http://img136.imageshack.us/img136/1538/exampleek5.png
You see how on the bottom, "Status" JPanel takes up the entire width of the window? When the window is resized, the border is also resized. I would love to have the top "Create" JPanel have the same behavior. How do I do this?
Thanks in advance!

It can get confusing when using the BoxLayout. The box layout takes into consideration the X alignment of the components as well as the minimum and maximum lengths.
So I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html]How to Use Box Layout for examples and explanations on how these values are used in the layout process.
It may be easier to use a BorderLayout for the high level layout manger, since it will resize a components width when added to the NORTH, CENTER or SOUTH.

Similar Messages

  • How to make a JPanel selectable

    When extending a JPanel and overriding the paintComponent() method the custom JPanel can not be selected so that it gets for example KeyEvents.
    But if I make the new Class extend a JButton it gets of course selected and able to receive for example KeyEvents.
    My question is therefore; what does the JButton implement that a JPanel doesn’t so that a JButton gets selectable? Or in other words; how to make a JPanel selectable?
    Aleksander.

    Try this extended code. Only the first panel added can get the Focus.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test extends JFrame
      public Test()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        ImagePanel imgPanel = new ImagePanel();
        panel1.setFocusable(true);
        panel2.setFocusable(true);
        panel1.setPreferredSize(new Dimension(0, 50));
        panel2.setPreferredSize(new Dimension(0, 50));
        panel1.setBorder(BorderFactory.createLineBorder(Color.RED,     4));
        panel2.setBorder(BorderFactory.createLineBorder(Color.CYAN,    4));
        imgPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
        panel1.add(new JLabel("Panel 1"), BorderLayout.CENTER);
        panel2.add(new JLabel("Panel 2"), BorderLayout.CENTER);
        getContentPane().add(panel1, BorderLayout.NORTH);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        getContentPane().add(imgPanel, BorderLayout.CENTER);   
        pack();
        panel1.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel1");}});
        panel2.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel2");}});
      public static void main(String[] args){new Test().setVisible(true);}
    class ImagePanel extends JPanel
      Image img;
      public ImagePanel()
        setFocusable(true);
        setPreferredSize(new Dimension(400,300));
        try{img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));}
        catch(Exception e){/*handled in paintComponent()*/}
        addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            System.out.println("ImagePanel");}});
      public void paintComponent(Graphics g)
        if(img != null)
          g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
        else
          g.drawString("This space for rent",50,50);
    }

  • How to make a completely transparent button in Flash Builder

    I am making a mobile application, and I am wondering how to make a completely transparent button. I've tried using
    <s:Button x="-5" y="0" width="410" height="1504"
                                    skinClass="spark.skins.mobile.TransparentNavigationButtonSkin" click="navigator.pushView(Sun)"/>
    But it still has one line on the side. I need a way to make it completely transparent.
    Thanks,
         8th grade student

    Try this alpha="0.001"
    Also add useHandCursor="true" and buttonMode="true" if you wish to have the hand cursor appear on hover.
    example  x="10" y="10" width="169" height="54" label="Button" alpha="0.001" useHandCursor="true" buttonMode="true" 
    HTH

  • How to make use of adjacent data elements within the same buffer

    Hi,
             Does anyone know how to make use of adjacent data elements within the same buffer? To make my question clearly, I would like to give you an example. In my application, I set "sample to read" as 10 which means at each loop 10 data samples will be taken into a buffer. Now, what I would like to do is to do some calculations on adjacent data samples in same buffer. I tried to use "shift register" for this, but it seemed to me that it only can deal with the calculation between data from adjacent loops. In other words, it skips 9 data elements and take the 10th one for the calculation.
             Here I also attach my VI showing what I did.
        Thank you very much in advance,
                            Suksun
    Attachments:
    wheel_encoder_1.vi ‏98 KB

    Hi Suksun,
          I hope you'll forgive me for distilling your code - mainly to understand it better.  I tried to duplicate your logic exactly - which required reversing the "derivatives"-array before concatination with the current samples array.  As in your code, the last velocity is being paired with the first position.  If first velocity is really supposed to be paired with first position, just remove the "Reverse 1D Array" node.
    cheers
    Message Edited by Dynamik on 01-07-2006 03:17 AM
    Message Edited by Dynamik on 01-07-2006 03:19 AM
    When they give imbeciles handicap-parking, I won't have so far to walk!
    Attachments:
    encoder2.GIF ‏14 KB
    encoder2.vi ‏102 KB

  • How to make a redirect without auto-redirect from the portlet "edit" mode?

    How to make a redirect without auto-redirect from the portlet "edit" mode?
    I use some sofisticated customizing with server-side validation of the form data. I want to redirect to the page of the portlet "show" mode and to the "edit" mode depending on the validation results. How can I do it?

    Heay.....this worked for me.
    I am able to change the mode programatically from edit to show.
    HttpPortletRendererUtil.handleEditAction(portletRenderRequest,"OK");
    I removed Apply , OK and Cancel buttons and applied my own Submit and Back button in Personalize mode and then change the mode to show on click of Back button using the above mentioned statement.
    Thanks
    ~Neeraj Sidhaye
    Try_Catch_Finally @ Y !
    ExtremePortal @ Gmail&#12288;&#65316;&#65359;&#65364;&#12288;&#65315;&#65359;&#65357;

  • How to make ENTER key in internet explorer run the  BIP report?

    In BI publisher 11g, users wanted that after entering the values for the parameter, they hit the ENTER key ( on the keyboard)  and the report should run .
    In Mozilla firefox, when I hit ENTER key on the keyboard report runs fine... but in Internet explorer, it does not ( infact in internet explorer TAB key works)
    How to make ENTER key in internet explorer run the report?
    Thanks
    Ashish

    Perform the following steps and tell us if it  resolve this issue:
    1. In Internet Explorer, click Tools, and then click Internet Options.
    2. Click the Security tab.
    3. There are four security zones listed:
    * Internet
    * Local intranet
    * Trusted sites
    * Restricted sites
    Click the zone being used by P6, which is noted at the bottom right hand corner of the browser window when the P6 URL is being accessed.
    4. Under Security level for this zone, click Custom Level.
    5. Under Downloads, under Automatic prompting for file downloads, click Enable, and then click OK two times.
    6. The browser will need to be restarted for the change to take effect.
    Refer to the following Microsoft Knowledge base article for additional file download and active x controls which should also be enabled: http://support.microsoft.com/kb/883255

  • How to make more than one person can access the database at one time

    how to make  more than one person can access the database at one time 

    Please post further f'up's in the Access forum.
    In short: for different reasons it is best practice that each user gets its own local copy of the database. This means that you need to split it into a front-end which only consists of the forms, queries, reports etc. Everything which doesn't need to be
    shared. And a back-end, which only stores the data.
    Take also a look at Allen Browne's article:
    Split your Access database into data and application.
    When you've splitted your database, you may often consider to use SQL Server as back-end. Here you may read Armen Stein's
    The Best of Both Worlds: Access-SQL Server Optimization.

  • How to make an ebook and sell it on the ibook or app store??

    How to make an ebook and sell it on the ibook or app store??
    Can anybody help me please T^T
    By the way I'm in Thailand and want to sell my ebook around the world.
    This is my dream ^^.. Help me please...

    Hi,
    Start with the ADC iOS dev center here.
    http://developer.apple.com/devcenter/ios/index.action
    Carolyn

  • Hi , How to make a calculated kf as local in the query definition

    Hi ,
    How to make a calculated kf as local in the query definition
    Regards,
    Ravi.

    Hi,
    Calculate KF consists of Basic, restrict and other calculated kFs stored in Metadata repository.
    Calculate KF is a replicate of Formula and acts as Global.
    Calculate KF acts as Global--you can use Globally.
    Formula as Local--you can use as local to Query.
    you can create the Calculate KF as follow:
    Goto Query Designer>Open/Create Query>Select Key Figures Mode on left side of Query>Select that KF node> right click Select Calculate Keyfigure.
    then one popup window dispays, so you make the calculations based on Basic KF, Restirct Kf and Formule. then save it.
    Regards,
    Suman.

  • Hello, i would like to know how to make horizontal sites and it moves with the scroll

    Hello, i would like to know how to make horizontal sites and it moves with the scroll

    Hi
    You can refer to these videos :
    http://www.lynda.com/Muse-tutorials/basics-horizontal-scrolling-websites/108131/115685-4.h tml
    https://www.youtube.com/watch?v=gZI_K1TXqOM
    Thanks,
    Sanjit

  • I updated iTunes to 10.4 version and now it doesn't start and sen a messages "iTunes has detected an error and must be closed". Someone have the same problem and how can we repair our installation insted of change the windows XP installation? Best regard

    I updated iTunes to 10.4 version and now it doesn't start and send a messages "iTunes has detected an error and must be closed". Someone have the same problem and how can we repair our installation insted of change the windows XP installation? Best regards

    Only way to get iMac starting again was to re-install 10.4.4 from DVD, and then update it into 10.4.6. For a while it worked perfectly, just as before.
    Then I tried to print to CD with my EPSON Stylus Photo 950 from Adobe Photoshop Elements (2.0). It didn't print anything, but printer started flashing all lights. The print job was not performed, so I did remove it from the Printer Utility. After that the iMac started "ticking" again, same noise than before, after 10.4.7 installation. I did re-boot iMac. It never started, it does stuck on gray screen (gray block running clockwise). HW test from DVD didn't find any problems (extended search looping 3 times). But Disk Utility found hard drive to have inaccurate node structure, it could not fix it.
    Apple support recommended to use DiskWarrior. However, it does not support (yet) Intel Macs. I haven't got TechTool Pro 4.5.1 anywhere. iMac does start on to FireWire mode (T at boot), but I cannot see the disk from 10.2.8 iMac.
    So, obvisously the problem is not 10.4.7. I believe it to be ESPON printer driver compatibility on Mac OSX. This does not suprise me, EPSON printers *****, I shall never purchase one again. However, disk catalog structure should not get messed by one faulty printer driver!

  • How do I set up my iCloud Email on the Windows 8 mail app?

    I'm not sure if I should be asking this on the Apple or Microsoft forums but I need to know how to set up my iCloud Mail address on the Windows 8 Mail app.  Can someone give me a detailed answer or a link to a website that can tell me?  Thanks guys.

    Try these settings: http://support.apple.com/kb/HT4864.

  • I am running Leopard 10.5.8 and want to partition Windows 7. The windows 7 I have is not a cd, I downloaded it. How do I install if I don't have the Windows 7 cd AND I don't have a PC to create a USB or CD?

    I am running Leopard 10.5.8 and want to partition Windows 7. The windows 7 I have is not a cd, I downloaded it. How do I install if I don't have the Windows 7 cd AND I don't have a PC to create a USB or CD?

    Thanks Fred. So I bought Snow Leopard, also installed ALL updates to now 10.6.8
    Problem: when I start my Boot Camp (3.0.4) it does not let me use a USB. I have been reading your article that I can be on a later Boot Camp but somehow Apple is not leading me where to actually download this Boot Camp Assistant upgrade.
    Keep in mind: every update on Apple about Boot Camp has been .exe which is useless to me since I do not have Windows installed.

  • How to make a JPanel with a GridLayout scroll

    I am using a JPanel to hold around 100 buttons. The JPanel is using GridLayout to organise these buttons in rows of 3 buttons per row. i.e. buttonPanel.setLayout(new GridLayout(33,3)); As there are so many buttons they obviously don't all fit in the viewable area of the screen. To get around this I am trying to use a JScrollPane on the buttonPanel to make it scroll but I can't get it to work. I have tried both creating a seperate JScrollPane object and adding the buttonPanel to it
    JScrollPane buttonScroll = new JScrollPane();
    buttonPanel.setLayout(new GridLayout(33,3));
    buttonPanel.setPreferredSize(new Dimension(380,400));
    buttonPanel.setMaximumSize(new Dimension(380,400));
    buttonScroll.add(buttonPanel);and also embeding everything into a new JPanel like:
    buttonHolder.add(new JScrollPane(buttonPanel),BorderLayout.CENTER);Neither way works. Any ideas. I've read about view port but not exactly sure what this is or if this will fix my problem.
    Help urgently required.

    Fixed layouts have their perils.
    We need to figure the size for the buttonScroll. Here's one way to approach this:
        topPanel
            messagePanel 400 x 400    buttonScroll unknown size
        inputPanel
            previewPane  600 x  80    sendButton   icon size (55 x 68, duke)
        For a fixed layout, find the size required for the buttonScroll by commenting out the
        two lines that add the buttons to buttonPanel and calling pack on the frame:
        frame size (pack w/no buttons)     743 x 570
        topPanel size                      735 x 400
        therefore, required size for
            buttonScroll is                335 x 400     (735 - 400, 400)
    After adding the buttons back in the final sizes become
    C:\jexp>java GUI
    frame width = 763       height = 570
    topPanel width = 755    height = 400I substituted a Duke image for your sendIcon so the sizes may differ but this should get you started...
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.Container.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class GUI extends JFrame
        Icon sendIcon = new ImageIcon(getClass().getResource("images/T4.gif"));
        Icon deleteIcon = new ImageIcon(getClass().getResource("images/T6.gif"));
        JButton sendButton = new JButton("Send",sendIcon);
        JButton deleteButton = new JButton("Delete",deleteIcon);
        JLabel statusBar = new JLabel();
        JMenu optionsMenu = new JMenu("Options");
        JMenu helpMenu = new JMenu("Help");
        JMenuBar menuBar = new JMenuBar();
        JMenuItem connectMenuItem = new JMenuItem("Connect");
        JMenuItem disconnectMenuItem = new JMenuItem("Disconnect");
        JMenuItem exitMenuItem = new JMenuItem("Exit");
        JMenuItem helpMenuItem = new JMenuItem("Online Help");
        JMenuItem aboutMenuItem = new JMenuItem("About");
        JPanel buttonPanel = new JPanel();
        JPanel inputPanel = new JPanel();
        JPanel messagePanel = new JPanel();
        JPanel topPanel = new JPanel();
        JPanel buttonHolder = new JPanel();
        JScrollPane buttonScroll = new JScrollPane(buttonPanel,20,30);
        JTextPane messageArea = new JTextPane();
        JTextPane previewPane = new JTextPane();
        public GUI()
            super("Chat Program");
            String userName = "user";
            statusBar.setText("Connected: " + userName);
            menuBar.add(optionsMenu);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            optionsMenu.add(connectMenuItem);
            optionsMenu.add(disconnectMenuItem);
            optionsMenu.add(exitMenuItem);
            helpMenu.add(helpMenuItem);
            helpMenu.add(aboutMenuItem);
            buttonPanel.setLayout(new GridLayout(0,3));
            for(int i = 0; i < 100; i++)
                buttonPanel.add(new JButton("Button " + (i + 1)));
            messageArea.setEditable(false);
            previewPane.setEditable(false);
            previewPane.setPreferredSize(new Dimension(600,80));
            previewPane.setMaximumSize(new Dimension(600,80));
            messagePanel.setLayout(new BorderLayout(10,10));
            messagePanel.add(new JScrollPane(messageArea),BorderLayout.CENTER);
            messagePanel.setPreferredSize(new Dimension(400,400));
            messagePanel.setMaximumSize(new Dimension(400,400));
            // w = 735 - 400, h = 400
            // does not take into account the width of the vertical scrollBar
            buttonScroll.setPreferredSize(new Dimension(335,400));       // *
            Box box = new Box(BoxLayout.X_AXIS);
            box.add(new JScrollPane(previewPane));
            box.add(sendButton);
            inputPanel.add(box,BorderLayout.CENTER);
            statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
            topPanel.setLayout(new BorderLayout(10,10));
            topPanel.add(messagePanel, BorderLayout.WEST);
            topPanel.add(buttonScroll, BorderLayout.EAST);
            Container content = getContentPane();
            content.add(topPanel,   BorderLayout.NORTH);
            content.add(inputPanel, BorderLayout.CENTER);
            content.add(statusBar,  BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
    //        setSize(?,?);       // 763, 570 (now we know)
            setLocation(200,200);
            setVisible(true);
            // collect size information
            System.out.println("frame width = " + getWidth() + "\t" +
                               "height = " + getHeight() + "\n" +
                               "topPanel width = " + topPanel.getWidth() + "\t" +
                               "height = " + topPanel.getHeight());
        public static void main(String[] args)
            new GUI();
    }

  • How to make a custom form, buttons etc... please...

    I mean, how to make a form (for example, JFrame) with arbitrary form (geometry, for ex, round, oval, star like etc). I think you understand what i mean.
    Of course, i think i can use winApi, but it's only for windows. It doesn't suit for Java in this problem solution.
    That question also about cusomizing form of buttons, fields.. etc..
    i think, everything.
    What can java allows to cusomize and what not.
    Thanx!!

    I am just a learner and so i can just suggest you a strategy to implement Customized forms in JAVA. However i am sure that in practice it will work as far as Windows OS are concerned. Here is it:-
    The basic IDEA is to declare a native function in JAVA that makes JNI calls which will be further processed by Win32API and processed output will result into an elliptic or any polygonal shaped forms.
    To achieve declare some function as follows:
    public native void createEllipticalForm(formName formRefrance);
    create a Win32 Compiled DLL that manages this function as follows:
    (Mindwell, i havent stated what you call as pure-code but just a pseudo-code to the actual implementation)
    public native void createEllipticalForm(formName formRefrance)
    /* Search for the below stated Functions in Win32 API and work on
    them. I see a ray of success if you work with these functions properly.
    Further-more I assume that you are aware with concept of HANDLES */
    createEllipticRegion(); //WINDOWS.H
    showWindow(handleToTheForm); //WINDOWS.H
    Search for "createEllipticRegion() or showWindow()" on the GOOGLE to get the pure win32 API Code for Creating Customized Forms.
    Reply me in case any of you people get a solution based on my idea.
    [by VISH]

Maybe you are looking for