JPanel Positiong with Gridbag Layout Problem

Hi,
I'm desingning an UI in which I made a JFrame and set it Layout as gridBag layout. Now I have added Three JPanel in this JFrame.
The problem is that All the three JPanels are shown in center While I want to palce them in top left corner.
I have done this through NetBeans 4.0 in the layout coustomize option I've set them in first in the left top most, second in below of the first and so on but when I run the application The JPanel are shown in the center in this Particular position i.e first at the top in center second below to the fist and so on.
Kindly solve my this problem.
Regards,
Danish Kamran.

To get better help sooner, post a SSCCE that clearly demonstrates your problem.
Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
db

Similar Messages

  • Gridbag layout problem on a tabbedpane

    I am not sure whether we can do this or not but, I am trying to have a gridbag layout on a TabbedPane object.
    I have a JFrame on which I am adding a TabbedPane object called "t" and on this TabbedPane I am adding a tab called "Insert" which is an object of class "Insert Data". Then, I add the TabbedPane t on the Container cp, which is inside the JFrame.
    In the InsertData Class (a JPanel), I need to have the gridbag layout. With this gridbag layout object, I am trying to place different objects like buttons, at various places, on this JPanel. But nothing moves on this panel.
    In short, please let me know how can I have a gridbag layout on a Tabbedpane.
    The Main Class is as follows:
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JTabbedPane;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Main extends JFrame implements ActionListener, ChangeListener{
         Main(){
                   setPreferredSize(new Dimension(1200,600));
                   Container cp = getContentPane();
                   JTabbedPane t = new JTabbedPane();
                   // insert
                   InsertData insertOptions = new InsertData();
                   t.addTab("Insert",insertOptions);
                   cp.add(t);
                   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   pack();
                   setVisible(true);
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
              @Override
              public void stateChanged(ChangeEvent arg0) {
                   // TODO Auto-generated method stub
              public static void main(String args[]){
                   new Main();
         }The InsertDataClass is:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class InsertData extends JPanel{
         InsertData(){
              setPreferredSize(new Dimension(1200,600));
              setBackground(Color.blue);
              //setLayout(new GridBagLayout());
              GridBagLayout gb = new GridBagLayout();
              setLayout(gb);
              GridBagConstraints c = new GridBagConstraints();
              //c.insets = new Insets(2, 2, 2, 2);
              //JPanel p1= new JPanel();
              //p1.setPreferredSize(new Dimension(200,200));
              JButton b1 = new JButton("here i am!!!");
              //p1.add(b1);
              //c.fill = GridBagConstraints.HORIZONTAL;
              //c.anchor = GridBagConstraints.WEST;
              c.gridx=0;
              c.gridy=1;
              add(b1,c);
    }

    how can I have a gridbag layout on a Tabbedpane.Huh? You post an example with just one JButton and no weightx / weighty set and you expect others here to be able to see a problem with your layout?
    Also, there's needless, unused code that is just clutter -- like the unimplemented ActionListener and ChaneListener. Recommended reading: [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html].
    Finally, I don't see any need whatsoever to extend JFrame and JPanel as you are not introducing any new behavior of either. Always favor composition over inheritance.
    I plugged in some code I had used for someone else's GridBagLayout problems and this will show you that there's no difference in using GridBagLayout in a tabbed pane component or anywhere else.import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.*;
    public class GridBagInTabbedPane {
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new GridBagInTabbedPane().makeUI();
      public void makeUI() {
        Font fontButton = new Font("Arial", Font.BOLD, 10);
        Font fontLabel = new Font("Arial", Font.BOLD, 15);
        JLabel labelEnter = new JLabel("Enter sentences in the text area ");
        labelEnter.setFont(fontLabel);
        JTextArea textArea = new JTextArea();
        textArea.setPreferredSize(new Dimension(630, 280));
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setMinimumSize(new Dimension(630, 280));
        JLabel labelDuplicates = new JLabel("Duplicates will appear here");
        labelDuplicates.setMinimumSize(new Dimension(650, 30));
        labelDuplicates.setFont(fontLabel);
        JButton buttonDisplay = new JButton("Display Map");
        buttonDisplay.setFont(fontButton);
        JButton buttonClear = new JButton("Clear");
        buttonClear.setFont(fontButton);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.weightx = 0.5;
        panel.add(labelEnter, gbc);
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weighty = 0.5;
        panel.add(scrollPane, gbc);
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weighty = 0.0;
        panel.add(labelDuplicates, gbc);
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(buttonDisplay, gbc);
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(buttonClear, gbc);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.add(panel);
        JFrame frame = new JFrame();
        frame.add(tabbedPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }db

  • Need help with a Layout problem

    I'm writing a game japplet, and I'd like to have the following layout:
    1 JPanel that takes up the whole screen
    1 JPanel on top of the first panel in the lower left corner
    1 JPanel on top of the first panel in the lower right corner
    What layout manager would be best for this system, or can I get away with just using setLocation()'s

    For a game, using a layout manager could not be the good solution... for example, if you have to draw a game area of fixed size, it's incompatible with a layout management which could reduce or grow the area's size.
    Personnally I would use the null layout solution... harder to code but much more reliable in this case!
    Good luck for your game... ;)
    Regards.

  • Trouble with gridbag layout

    I have been experimenting with this container, but i cant work a couple of things out. I have set the size of my application quite large, 800, 600.
    I am trying to get my end result to look somthing like this
    SWIMMING
    100M 200M 400M
    So i have declared and initialised my components, and then i have done this to put them in the layout.
    GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
         gridBagConstraintsx01.gridx = 0;
         gridBagConstraintsx01.gridy = 0;
         gridBagConstraintsx01.insets = new Insets(5,5,5,5);
         cPane.add(lbSwimming, gridBagConstraintsx01);  //JLabel
         GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
         gridBagConstraintsx02.gridx = 0;
         gridBagConstraintsx02.insets = new Insets(5,5,5,5);
         gridBagConstraintsx02.gridy = 1;
         gridBagConstraintsx02.gridwidth = 2;
         gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
         cPane.add(eveSwim50M, gridBagConstraintsx02);  //JButton
         GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
         gridBagConstraintsx03.gridx = 1;
         gridBagConstraintsx03.insets = new Insets(5,5,5,5);
         gridBagConstraintsx03.gridy = 1;
         gridBagConstraintsx03.gridwidth = 2;
         gridBagConstraintsx03.fill = GridBagConstraints.BOTH;
         cPane.add(eveSwim100M, gridBagConstraintsx03);  //JButton
         GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
         gridBagConstraintsx04.gridx = 2;
         gridBagConstraintsx04.insets = new Insets(5,5,5,5);
         gridBagConstraintsx04.gridy = 1;
         gridBagConstraintsx04.gridwidth = 2;
         gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
         cPane.add(eveSwim200M, gridBagConstraintsx04);  //JButtonMy first problem is that everything has been put in the middle of my application, where i was hoping it would start in the top left. I thought that gridx0 and gridy0 would start it from this, but obviously this doesnt seem to be the case. How would i place it in the top left? My second problem is that my buttons are overlapping eachother and have not been seperated. I thought the fill would take care of this but once again it does not seemed to have worked. What would i use to give each button its space? Also, if you can see any improvements i could make, please advise me and i will make them.
    Cheers for the help

    I have changed it to be more like
        lbMulti.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 7;
        gridBagConstraints.ipadx = 36;
        gridBagConstraints.ipady = 6;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(27, 27, 0, 0);
        getContentPane().add(lbMulti, gridBagConstraints);Getting closer to what i need, but i am going to take your advise and steer clear of gridbag, way too over the top. The only problem is that i cant really find another layout that will layout the way i want it too. I am checking in netbeans how each layout will look. If you can advise me what layout you prefere to use and then i could see if i could redesign my dialog around this.
    cheers

  • Help needed with a layout problem

    I'm trying to build a JTabbedPane where each tab has a grid of buttons. The number of buttons is variable, and I'd like the buttons to flow sort of like with FlowLayout, with four columns. I need all the buttons to be the same size, even across tabs. I tried GridLayout, which doesn't work when I have too few buttons to fill a row. It fails in different ways, depending on how I set things up. If I try to set the layout to GridLayout(0, 4) (four columns), then if one tab has one row and another has two, the buttons on the one-row tab expand vertically to the height of the two-row tab. If I try GridLayout(2,4), then if a tab has only one button, it expands horizontally to the maximum width of any of the tabs. (It also has the further problem that if the maximum number of buttons on any tab is 6, they are placed in a 2x3 array; I'm trying to get them to be 4 buttons on the first row and 2 on the second.)
    I'm hoping there's a standard layout manager that can do the job, but I'm not too familiar with the Swing manager classes. Can I get what I want without writing my own layout manager?
    Thanks,
    Ted Hopp
    [email protected]

    I didn't think it was specifically a Swing question.Well, its either Swing or AWT, people who develop GUIs are the ones who are going to have experience using layout managers.
    but if someone can point the way to how to do this with GridBagLayout, nested containersSince you finished reading the tutorial, what have you tried? You've explained your problems using a single layout manager, so what problems are you having using nested layout managers?
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Site with tables layout problem

    Hello,
    I am hoping someone could help me with likely a stupid error
    on my part. It is with a site I just started to rework;
    www.starprecision.com. I am hoping you may think it is obvious as
    to why:
    1. There is a shift to the left for pages "home",
    "company>employment opportunities" and "company>contact us"
    with respect to the other pages. This, for instance, occurs in
    Opera and FireFox. However not in IE7.
    2. The dotted rectangular outline of the graphi appears
    around the "prev" and "next" buttons when they are pressed in IE7
    and FireFox but not in Opera.
    3. The darned site won't even come up in Safari.
    4. I want to redo the site based on a css template. Might one
    suggest a starting template for this site?
    Thank you for any guidance you may be able to provide.
    take care,
    john

    First, fix these -
    http://validator.w3.org/check?verbose=1&uri=http%3A%2F%2Fwww.starprecision.com%2Femploymen t.shtml
    Most of those 40 errors will be fixed by aligning your page's
    doctype with
    the HTML tag syntax you are using. In DW CS3 or CS4, you
    could do this
    easily by opening the page and then using FILE | Convert >
    HTML 4.01
    Transitional.
    Also, you need this line - why is it commented out?
    <!--<meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1">
    -->
    > 1. There is a shift to the left for pages "home",
    "company>employment
    > opportunities" and "company>contact us" with respect
    to the other pages.
    > This,
    > for instance, occurs in Opera and FireFox. However not
    in IE7.
    Add this to your CSS -
    html, body { min-height:100%;margin-bottom:1px; }
    It will force every page to have a vertical scrollbar, not
    just those with
    long content. It's the appearance of this scrollbar that is
    causing the
    left/right shift.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "johnarvy" <[email protected]> wrote in
    message
    news:[email protected]...
    > Hello,
    >
    > I am hoping someone could help me with likely a stupid
    error on my part.
    > It
    > is with a site I just started to rework;
    www.starprecision.com. I am
    > hoping
    > you may think it is obvious as to why:
    >
    > 1. There is a shift to the left for pages "home",
    "company>employment
    > opportunities" and "company>contact us" with respect
    to the other pages.
    > This,
    > for instance, occurs in Opera and FireFox. However not
    in IE7.
    >
    > 2. The dotted rectangular outline of the graphi appears
    around the "prev"
    > and
    > "next" buttons when they are pressed in IE7 and FireFox
    but not in Opera.
    >
    > 3. The darned site won't even come up in Safari.
    >
    > 4. I want to redo the site based on a css template.
    Might one suggest a
    > starting template for this site?
    >
    > Thank you for any guidance you may be able to provide.
    >
    > take care,
    > john
    >

  • CSS Layout Problem?

    Can someone please help me with a layout problem.
    As far as I can tell the page looks as it should in Netscape,
    Firefox, etc., but IE6 and 7 refuse to work correctly.
    The page I am working on is:
    http://www.vmtampademo.com/localangler/testpage.html
    Most of the picture caption and headline of the middle column
    is behind the picture. I attempted to force the info with a
    seperating div which seems to work sometimes. I doubt that this is
    the correct solution. What am I doing wrong?
    Thank you for the help!

    It looks fine in Firefox 2.0.0.1, Opera 9.10, and IE 7.

  • Possible Problem/Bug In GridBag Layout ????

    I've done hundreds of Gridbag layouts in the past 2 years and just noticed this weird little behavior today.....
    Basically what I'm trying to do is arrange panels like this.....
    +--------+--------+--------+
    |        |        |        |
    |   A    |    B   |   C    |
    |        |        |        |
    +--------+----+---+--------+
    |             |            |
    |     D       |      E     |
    |             |            |
    +-------------+------------+The obvious thing to do is to
    o make the gridwidths of
    B, D, E = 2
    A, C = 1
    D and E should each share one unit of
    B's 2 width.
    Tried it in my code with my real UI and it didn't work, so then I tested it
    out using a Gridbag tool where you can set parameters on the fly quickly and
    surely enough it did not work there either.
    The GridBagLayout is refusing to split B into 2 portions for the 2nd row
    to use in an unalligned fashion. I either get
    +--------+--------+--------+
    |        |        |        |
    |   A    |    B   |   C    |
    |        |        |        |
    +--------+----+---+--------+
    |        |                 |
    |     D  |           E     |
    |        |                 |
    +--------+-----------------+  or
    +--------+--------+--------+
    |        |        |        |
    |   A    |    B   |   C    |
    |        |        |        |
    +--------+----+---+--------+
    |                 |        |
    |     D           |  E     |
    |                 |        |
    +--------+--------+--------+ depending on the order in which I add my panels to the layout.
    even though my gridx, gridy and widths and heights are properly set for
    obtaining the result I want.
    Can someone confirm that this is a bug in the GridBagLayout or share the trick for
    getting around this?

    Thanks for the reply - I can set the weights however
    I wish and I never see box D extending even one pixel
    into the A-B boundary.This does what you say...
    import java.awt.*;
    import javax.swing.*;
    public class TestFrame extends JFrame {
      public TestFrame() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weighty = 0.5; 
        panel.add(new JButton("A"), gbc);
        gbc.gridx = 1;   
        gbc.gridwidth = 2; 
        panel.add(new JButton("B"), gbc);
        gbc.gridx = 3;   
        gbc.gridwidth = 1;
        panel.add(new JButton("C"), gbc);
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        gbc.weightx = 0.5;
        panel.add(new JButton("D"), gbc);
        gbc.gridx = 2;
        panel.add(new JButton("E"), gbc);
        getContentPane().add(panel);
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      public static void main(String[] args) {
        TestFrame frame = new TestFrame();
        frame.setVisible(true);
    }But i'm sure it's not a satisfactory layout because button A does not want to resize horizontally at all. But of course, a mix of grid layouts does the trick:
    import java.awt.*;
    import javax.swing.*;
    public class TestFrame extends JFrame {
      public TestFrame() {
        JPanel panel = new JPanel(new GridLayout(2, 1));
        JPanel top = new JPanel(new GridLayout(1, 3));
        top.add(new JButton("A"));
        top.add(new JButton("B"));
        top.add(new JButton("C"));
        panel.add(top);
        JPanel buttom = new JPanel(new GridLayout(1, 2));
        buttom.add(new JButton("D"));
        buttom.add(new JButton("E"));
        panel.add(buttom);
        getContentPane().add(panel);
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      public static void main(String[] args) {
        TestFrame frame = new TestFrame();
        frame.setVisible(true);
    }

  • Gridbag layout in jpanel?

    Hi, all
    I just start to use gridbag layout in my application. It looks very like table in html to me. While writing html table, I can use 'border=1' to determine width and height for each cell. Is it possible to reveal border of each grid in jpanel?
    Thanks,

    You can't reveal the border of the cells being used by GridBagLayout.
    You could add a LineBorder to each component but this won't show you the cell border, it will show you the component border. There could be padding between the component and the cell boundary.
    However, you should try to avoid thinking of GridBagLayout as being like an HTML table; this usually causes confusion. There's probably a number of topics in this forum about wanting to get HTML table behaviour with a GridBagLayout.
    Here's one for a start:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=251815

  • Problems with the Layout Priority in KM

    Hello, I have some problems with the Layout Priority in KM..
    I'm using a KM Navigation Iview with "<i>Layout Set</i>"=NewsBrowser (this Layout Set uses a Collection renderer that sorts the folder's contents by "last modified") and "<i>Layout Set Mode</i>"=exclusive.
    In the KM folder I setted in <i>Details->Settings->Presentation</i> as "<u>rndSortProperty</u>"=name because I need to order my files by FileName property.
    Despite that in see that the contents showed in my iview are ordered by Last Modified...
    The "<i>Layout Set Mode</i>" exclusive gives the higher priority to the Folder Settings..
    I don't understand..
    Thank you in advance.

    Thank you Shyja,
    your post was helpful, but another issue is occurred.
    Maybe en example could be useful..
    My scenario:
    - I need to show a km folder with layout set "<i>ConsumerExplorer</i>" on root folder (no "property of sorting" setted on its collection renderer) and "<i>TabExplorer</i>" (no "property of sorting" setted on its collection renderer).
    - I need to sort files and folders by "last modified". By default seems that they are sorted by "name".
    - With my administrator user I open my folder details (in Content Admin->KM Content is used the Layout "<i>AdminExplorer</i>"), and in "Settings->Presentation->Additional Parameters" I add two parameters "<i>rndSortOrder</i>=descending" and "<i>rndSortProperty</i>=modified" (the others are parameters of AdminExplorer Layout).
    - Then I check "Apply Settings to All Subfolders" and "Use Settings for All iViews (Preferred Presentation)".
    result:
    I see the "<i>ConsumerExplorer</i>" on root folder, the subfolder are sorted by "last modified" (everything ok).
    I click on a subfolder, the "TabExplorer" si showed, the Tabs and the content are sorted by "last modified" BUT..
    .. into the tabs are showed <u>nameFolders</u> (in link style), <u>the action command</u>, and the properties of "<u>author</u>" and "<u>last modified</u>" (normally into the tabs are showed just the folderNames in text style)...
    Why?? Is possible that the "AdminExplorer" parameters of the km folder affect the Tab component??
    Thank you

  • Tool bar dock problem with grid layout

    I have a tool bar with grid layout. When i dock it to vertical location(west or east) the buttons inside tool bar keep one row. I want to know how do i do to make the buttons arraged vertically like the tool bar with default layout when dock it at west or east position.

    I had started a custom layout manager for toolbars a few months ago that I found a little easier to use than the default BoxLayout. I just modified it to allow optionally matching the button sizes (width, height, or both), so you can get the same effect as GridLayout. Note that this one doesn't collapse the toolbar like the one in the other thread. Here's the source code as well as a simple test app to demonstrate how to use it. Hope it helps.
    //     TestApp.java
    //     Test application for ToolBarLayout
    // package ***;
    import java.awt.*;
    import javax.swing.*;
    public class TestApp extends JFrame
         /////////////////////// Main Method ///////////////////////
         public static void main(String[] args)
              try { UIManager.setLookAndFeel(
                   UIManager.getSystemLookAndFeelClassName()); }
              catch(Exception ex) { }     
              new TestApp();
         public TestApp()
              setTitle("ToolBarLayout Test");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setSize(400, 300);
              setLocationRelativeTo(null);
              JToolBar tbar = new JToolBar();
              ToolBarLayout layout = new ToolBarLayout(tbar);
              // Comment these two lines out one at a time to see
              // how they affect the toolbar's layout...
              layout.setMatchesComponentDepths(true);
              layout.setMatchesComponentLengths(true);
              tbar.setLayout(layout);
              tbar.add(new JButton("One"));
              tbar.add(new JButton("Two"));
              tbar.add(new JButton("Three"));
              tbar.addSeparator();
              tbar.add(new JButton("Musketeers"));
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              c.add(tbar, BorderLayout.NORTH);
              setVisible(true);
    //     ToolBarLayout.java
    //     A simple layout manager for JToolBars.  Optionally resizes buttons to
    //     equal width or height based on the maximum preferred width or height
    //     of all components.
    // package ***;
    import java.awt.*;
    import javax.swing.*;
    public class ToolBarLayout implements LayoutManager, SwingConstants
         private JToolBar     oToolBar = null;
         private boolean     oMatchDepth = false;
         private boolean     oMatchLength = false;
         private int          oGap = 0;
         public ToolBarLayout(JToolBar toolBar)
              oToolBar = toolBar;
         public ToolBarLayout(JToolBar toolBar, boolean matchDepths)
              oToolBar = toolBar;
              oMatchDepth = matchDepths;
         public ToolBarLayout(JToolBar toolBar,
                        boolean matchDepths,
                             boolean matchLengths)
              oToolBar = toolBar;
              oMatchDepth = matchDepths;
              oMatchLength = matchLengths;
         // If true, all buttons in the row will be sized to
         // the same height (assuming horizontal orientation)
         public void setMatchesComponentDepths(boolean match)
              oMatchDepth = match;
         // If true, all buttons in the row will be sized to
         // the same width (assuming horizontal orientation)
         public void setMatchesComponentLengths(boolean match)
              oMatchLength = match;
         public void setSpacing(int spacing)
              oGap = Math.max(0, spacing);
         public int getSpacing()
              return oGap;
         ////// LayoutManager implementation //////
         public void addLayoutComponent(String name, Component comp) { }
         public void removeLayoutComponent(Component comp) { }
         public Dimension minimumLayoutSize(Container parent)
              return preferredLayoutSize(parent);
         public Dimension preferredLayoutSize(Container parent)
              synchronized (parent.getTreeLock())
                   int orientation = getOrientation();
                   Component[] components = parent.getComponents();
                   int w = 0, h = 0;
                   int totalWidth = 0, totalHeight = 0;
                   int maxW = getMaxPrefWidth(components);
                   int maxH = getMaxPrefHeight(components);
                   Dimension ps = null;
                   if (orientation == HORIZONTAL)
                        for (int i=0; i < components.length; i++)
                             ps = components.getPreferredSize();
                             if (oMatchLength) w = maxW;
                             else w = ps.width;
                             if (oMatchDepth) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = ps.width;
                                  h = 0;
                             totalWidth += w;
                             if (i < components.length - 1)
                                       totalWidth += oGap;
                             totalHeight = Math.max(totalHeight, h);
                   else
                        for (int i=0; i < components.length; i++)
                             ps = components[i].getPreferredSize();
                             if (oMatchDepth) w = maxW;
                             else w = ps.width;
                             if (oMatchLength) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = 0;
                                  h = ps.height;
                             totalHeight += h;
                             if (i < components.length - 1)
                                       totalHeight += oGap;
                             totalWidth = Math.max(totalWidth, w);
                   Insets in = parent.getInsets();
                   totalWidth += in.left + in.right;
                   totalHeight += in.top + in.bottom;
                   return new Dimension(totalWidth, totalHeight);
         public void layoutContainer(Container parent)
              synchronized (parent.getTreeLock())
                   int orientation = getOrientation();
                   Component[] components = parent.getComponents();
                   Insets in = parent.getInsets();
                   int x = in.left, y = in.top;
                   int w = 0, h = 0, maxW = 0, maxH = 0;
                   Dimension ps = null;
                   if (orientation == HORIZONTAL)
                        maxW = getMaxPrefWidth(components);
                        maxH = Math.max( getMaxPrefHeight(components),
                             parent.getHeight() - in.top - in.bottom );
                        for (int i=0; i < components.length; i++)
                             ps = components[i].getPreferredSize();
                             if (oMatchLength) w = maxW;
                             else w = ps.width;
                             if (oMatchDepth) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = ps.width;
                                  h = maxH;
                             components[i].setBounds(
                                  x, y + (maxH-h)/2, w, h);
                             x += w + oGap;
                   else
                        maxH = getMaxPrefHeight(components);
                        maxW = Math.max( getMaxPrefWidth(components),
                             parent.getWidth() - in.left - in.right );
                        for (int i=0; i < components.length; i++)
                             ps = components[i].getPreferredSize();
                             if (oMatchDepth) w = maxW;
                             else w = ps.width;
                             if (oMatchLength) h = maxH;
                             else h = ps.height;
                             if (components[i] instanceof JSeparator)
                                  w = maxW;
                                  h = ps.height;
                             components[i].setBounds(
                                  x + (maxW-w)/2, y, w, h);
                             y += h + oGap;
         //// private methods ////
         private int getOrientation()
              if (oToolBar != null) return oToolBar.getOrientation();
              else return HORIZONTAL;
         private int getMaxPrefWidth(Component[] components)
              int maxWidth = 0;
              int componentWidth = 0;
              Dimension d = null;
              for (int i=0; i < components.length; i++)
                   d = components[i].getPreferredSize();
                   componentWidth = d.width;
                   if (components[i] instanceof JSeparator)
                        componentWidth = Math.min(d.width, d.height);
                   maxWidth = Math.max(maxWidth, componentWidth);
              return maxWidth;
         private int getMaxPrefHeight(Component[] components)
              int maxHeight = 0;
              int componentHeight = 0;
              Dimension d = null;
              for (int i=0; i < components.length; i++)
                   d = components[i].getPreferredSize();
                   componentHeight = d.height;
                   if (components[i] instanceof JSeparator)
                        componentHeight = Math.min(d.width, d.height);
                   else maxHeight = Math.max(maxHeight, componentHeight);
              return maxHeight;

  • Yet Another Key Layout Problem with Xorg7

    I've read the wiki and forums, yet I haven't managed to get @-sign nor  |-sign working with my finnish keyboard. Both need the compose key. Any pointers to relevant info or suggestions how to remedy this are most welcomed!
    Here's my xorg.conf if it's any help:
    Section "ServerLayout"
    Identifier "XFree86 Configured"
    Screen 0 "Screen0" 0 0
    InputDevice "Keyboard0" "CoreKeyboard"
    InputDevice "USB Mouse" "CorePointer"
    EndSection
    Section "ServerFlags"
    Option "AllowMouseOpenFail" "true"
    EndSection
    Section "Files"
    RgbPath "/usr/share/X11/rgb"
    ModulePath "/usr/lib/xorg/modules"
    FontPath "/usr/share/fonts/misc:unscaled"
    FontPath "/usr/share/fonts/misc"
    FontPath "/usr/share/fonts/75dpi:unscaled"
    FontPath "/usr/share/fonts/75dpi"
    FontPath "/usr/share/fonts/100dpi:unscaled"
    FontPath "/usr/share/fonts/100dpi"
    FontPath "/usr/share/fonts/Speedo"
    FontPath "/usr/share/fonts/PEX"
    # Additional fonts: Locale, Gimp, TTF...
    FontPath "/usr/share/fonts/cyrillic"
    # FontPath "/usr/share/fonts/latin2/75dpi"
    # FontPath "/usr/share/fonts/latin2/100dpi"
    # True type and type1 fonts are also handled via xftlib, see /etc/X11/XftConfig! FontPath "/usr/share/fonts/Type1"
    FontPath "/usr/share/fonts/ttf/western"
    FontPath "/usr/share/fonts/ttf/decoratives"
    FontPath "/usr/share/fonts/truetype"
    FontPath "/usr/share/fonts/truetype/openoffice"
    FontPath "/usr/share/fonts/truetype/ttf-bitstream-vera"
    FontPath "/usr/share/fonts/latex-ttf-fonts"
    FontPath "/usr/share/fonts/defoma/CID"
    FontPath "/usr/share/fonts/defoma/TrueType"
    EndSection
    Section "Module"
    # Load "ddc" # ddc probing of monitor
    # Load "GLcore"
    Load "dbe"
    # Load "dri"
    Load "extmod"
    Load "glx"
    Load "bitmap" # bitmap-fonts
    # Load "speedo"
    Load "type1"
    Load "freetype"
    Load "record"
    EndSection
    Section "InputDevice"
    Identifier "Keyboard0"
    Driver "keyboard"
    Option "CoreKeyboard"
    Option "XkbRules" "xorg"
    Option "XkbModel" "pc105"
    Option "XkbLayout" "fi"
    Option "XkbOptions" "compose:ralt"
    EndSection
    Section "InputDevice"
    Identifier "USB Mouse"
    Driver "mouse"
    Option "Device" "/dev/input/mice"
    Option "SendCoreEvents" "true"
    Option "Protocol" "IMPS/2"
    Option "ZAxisMapping" "4 5"
    Option "Buttons" "5"
    EndSection
    Section "Monitor"
    Identifier "Monitor0"
    VendorName "MEI"
    ModelName "MEI0c95"
    HorizSync 30 - 70 # DDC-probed
    VertRefresh 50 - 160 # DDC-probed
    EndSection
    Section "Device"
    Identifier "Card0"
    Driver "nvidia"
    VendorName "All"
    BoardName "All"
    EndSection
    Section "Screen"
    Identifier "Screen0"
    Device "Card0"
    Monitor "Monitor0"
    DefaultColorDepth 24
    SubSection "Display"
    Depth 1
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    SubSection "Display"
    Depth 4
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    SubSection "Display"
    Depth 8
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    SubSection "Display"
    Depth 15
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    SubSection "Display"
    Depth 16
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    SubSection "Display"
    Depth 24
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    SubSection "Display"
    Depth 32
    Modes "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
    EndSection
    #Section "DRI"
    # Mode 0666
    #EndSection

    I tried if regenerating the file with xorgconfig would help. It didn't. I'm still missing AltGr functionality even if I do have:
    Option "XkbOptions" ctrl:ctrl_aa,altwin:meta_win,compose:ralt,eurosign:e"
    Any Ideas?
    # File generated by xorgconfig.
    # Copyright 2004 The X.Org Foundation
    # Permission is hereby granted, free of charge, to any person obtaining a
    # copy of this software and associated documentation files (the "Software"),
    # to deal in the Software without restriction, including without limitation
    # the rights to use, copy, modify, merge, publish, distribute, sublicense,
    # and/or sell copies of the Software, and to permit persons to whom the
    # Software is furnished to do so, subject to the following conditions:
    # The above copyright notice and this permission notice shall be included in
    # all copies or substantial portions of the Software.
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    # The X.Org Foundation BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
    # OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    # SOFTWARE.
    # Except as contained in this notice, the name of The X.Org Foundation shall
    # not be used in advertising or otherwise to promote the sale, use or other
    # dealings in this Software without prior written authorization from
    # The X.Org Foundation.
    # Refer to the xorg.conf(5x) man page for details about the format of
    # this file.
    # Module section -- this section is used to specify
    # which dynamically loadable modules to load.
    Section "Module"
    # This loads the DBE extension module.
    Load "dbe" # Double buffer extension
    # This loads the miscellaneous extensions module, and disables
    # initialisation of the XFree86-DGA extension within that module.
    SubSection "extmod"
    Option "omit xfree86-dga" # don't initialise the DGA extension
    EndSubSection
    # This loads the font modules
    Load "type1"
    # Load "speedo"
    Load "freetype"
    # Load "xtt"
    # This loads the GLX module
    Load "glx"
    # This loads the DRI module
    # Load "dri"
    EndSection
    # Files section. This allows default font and rgb paths to be set
    Section "Files"
    # The location of the RGB database. Note, this is the name of the
    # file minus the extension (like ".txt" or ".db"). There is normally
    # no need to change the default.
    RgbPath "/usr/lib/X11/rgb"
    # Multiple FontPath entries are allowed (which are concatenated together),
    # as well as specifying multiple comma-separated entries in one FontPath
    # command (or a combination of both methods)
    FontPath "/usr/share/fonts/misc"
    FontPath "/usr/share/fonts/75dpi"
    FontPath "/usr/share/fonts/100dpi"
    FontPath "/usr/share/fonts/TTF"
    FontPath "/usr/share/fonts/Type1"
    # FontPath "/usr/lib/X11/fonts/local/"
    # FontPath "/usr/lib/X11/fonts/misc/"
    # FontPath "/usr/lib/X11/fonts/75dpi/:unscaled"
    # FontPath "/usr/lib/X11/fonts/100dpi/:unscaled"
    # FontPath "/usr/lib/X11/fonts/Speedo/"
    # FontPath "/usr/lib/X11/fonts/Type1/"
    # FontPath "/usr/lib/X11/fonts/TrueType/"
    # FontPath "/usr/lib/X11/fonts/freefont/"
    # FontPath "/usr/lib/X11/fonts/75dpi/"
    # FontPath "/usr/lib/X11/fonts/100dpi/"
    # The module search path. The default path is shown here.
    # ModulePath "/usr/lib/modules"
    EndSection
    # Server flags section.
    Section "ServerFlags"
    # Uncomment this to cause a core dump at the spot where a signal is
    # received. This may leave the console in an unusable state, but may
    # provide a better stack trace in the core dump to aid in debugging
    # Option "NoTrapSignals"
    # Uncomment this to disable the <Ctrl><Alt><Fn> VT switch sequence
    # (where n is 1 through 12). This allows clients to receive these key
    # events.
    # Option "DontVTSwitch"
    # Uncomment this to disable the <Ctrl><Alt><BS> server abort sequence
    # This allows clients to receive this key event.
    # Option "DontZap"
    # Uncomment this to disable the <Ctrl><Alt><KP_+>/<KP_-> mode switching
    # sequences. This allows clients to receive these key events.
    # Option "Dont Zoom"
    # Uncomment this to disable tuning with the xvidtune client. With
    # it the client can still run and fetch card and monitor attributes,
    # but it will not be allowed to change them. If it tries it will
    # receive a protocol error.
    # Option "DisableVidModeExtension"
    # Uncomment this to enable the use of a non-local xvidtune client.
    # Option "AllowNonLocalXvidtune"
    # Uncomment this to disable dynamically modifying the input device
    # (mouse and keyboard) settings.
    # Option "DisableModInDev"
    # Uncomment this to enable the use of a non-local client to
    # change the keyboard or mouse settings (currently only xset).
    # Option "AllowNonLocalModInDev"
    EndSection
    # Input devices
    # Core keyboard's InputDevice section
    Section "InputDevice"
    Identifier "Keyboard1"
    Driver "kbd"
    # For most OSs the protocol can be omitted (it defaults to "Standard").
    # When using XQUEUE (only for SVR3 and SVR4, but not Solaris),
    # uncomment the following line.
    # Option "Protocol" "Xqueue"
    Option "AutoRepeat" "500 30"
    # Specify which keyboard LEDs can be user-controlled (eg, with xset(1))
    # Option "Xleds" "1 2 3"
    # Option "LeftAlt" "Meta"
    # Option "RightAlt" "ModeShift"
    # To customise the XKB settings to suit your keyboard, modify the
    # lines below (which are the defaults). For example, for a non-U.S.
    # keyboard, you will probably want to use:
    # Option "XkbModel" "pc105"
    # If you have a US Microsoft Natural keyboard, you can use:
    # Option "XkbModel" "microsoft"
    # Then to change the language, change the Layout setting.
    # For example, a german layout can be obtained with:
    # Option "XkbLayout" "de"
    # or:
    # Option "XkbLayout" "de"
    # Option "XkbVariant" "nodeadkeys"
    # If you'd like to switch the positions of your capslock and
    # control keys, use:
    # Option "XkbOptions" "ctrl:swapcaps"
    # These are the default XKB settings for Xorg
    # Option "XkbRules" "xorg"
    # Option "XkbModel" "pc105"
    # Option "XkbLayout" "us"
    # Option "XkbVariant" ""
    # Option "XkbOptions" ""
    # Option "XkbDisable"
    Option "XkbRules" "xorg"
    Option "XkbModel" "pc105"
    Option "XkbLayout" "fi"
    Option "XkbOptions" "ctrl:ctrl_aa,altwin:meta_win,compose:ralt,eurosign:e"
    EndSection
    # Core Pointer's InputDevice section
    Section "InputDevice"
    # Identifier and driver
    Identifier "Mouse1"
    Driver "mouse"
    Option "Protocol" "IMPS/2" # IntelliMouse PS/2
    Option "Device" "/dev/input/mice"
    # When using XQUEUE, comment out the above two lines, and uncomment
    # the following line.
    # Option "Protocol" "Xqueue"
    # Mouse-speed setting for PS/2 mouse.
    # Option "Resolution" "256"
    # Baudrate and SampleRate are only for some Logitech mice. In
    # almost every case these lines should be omitted.
    # Option "BaudRate" "9600"
    # Option "SampleRate" "150"
    # Mouse wheel mapping. Default is to map vertical wheel to buttons 4 & 5,
    # horizontal wheel to buttons 6 & 7. Change if your mouse has more than
    # 3 buttons and you need to map the wheel to different button ids to avoid
    # conflicts.
    Option "ZAxisMapping" "4 5 6 7"
    # Emulate3Buttons is an option for 2-button mice
    # Emulate3Timeout is the timeout in milliseconds (default is 50ms)
    # Option "Emulate3Buttons"
    # Option "Emulate3Timeout" "50"
    # ChordMiddle is an option for some 3-button Logitech mice
    # Option "ChordMiddle"
    EndSection
    # Other input device sections
    # this is optional and is required only if you
    # are using extended input devices. This is for example only. Refer
    # to the xorg.conf man page for a description of the options.
    # Section "InputDevice"
    # Identifier "Mouse2"
    # Driver "mouse"
    # Option "Protocol" "MouseMan"
    # Option "Device" "/dev/mouse2"
    # EndSection
    # Section "InputDevice"
    # Identifier "spaceball"
    # Driver "magellan"
    # Option "Device" "/dev/cua0"
    # EndSection
    # Section "InputDevice"
    # Identifier "spaceball2"
    # Driver "spaceorb"
    # Option "Device" "/dev/cua0"
    # EndSection
    # Section "InputDevice"
    # Identifier "touchscreen0"
    # Driver "microtouch"
    # Option "Device" "/dev/ttyS0"
    # Option "MinX" "1412"
    # Option "MaxX" "15184"
    # Option "MinY" "15372"
    # Option "MaxY" "1230"
    # Option "ScreenNumber" "0"
    # Option "ReportingMode" "Scaled"
    # Option "ButtonNumber" "1"
    # Option "SendCoreEvents"
    # EndSection
    # Section "InputDevice"
    # Identifier "touchscreen1"
    # Driver "elo2300"
    # Option "Device" "/dev/ttyS0"
    # Option "MinX" "231"
    # Option "MaxX" "3868"
    # Option "MinY" "3858"
    # Option "MaxY" "272"
    # Option "ScreenNumber" "0"
    # Option "ReportingMode" "Scaled"
    # Option "ButtonThreshold" "17"
    # Option "ButtonNumber" "1"
    # Option "SendCoreEvents"
    # EndSection
    # Monitor section
    # Any number of monitor sections may be present
    Section "Monitor"
    Identifier "Monitor0"
    # HorizSync is in kHz unless units are specified.
    # HorizSync may be a comma separated list of discrete values, or a
    # comma separated list of ranges of values.
    # NOTE: THE VALUES HERE ARE EXAMPLES ONLY. REFER TO YOUR MONITOR'S
    # USER MANUAL FOR THE CORRECT NUMBERS.
    HorizSync 30-70
    # HorizSync 30-64 # multisync
    # HorizSync 31.5, 35.2 # multiple fixed sync frequencies
    # HorizSync 15-25, 30-50 # multiple ranges of sync frequencies
    # VertRefresh is in Hz unless units are specified.
    # VertRefresh may be a comma separated list of discrete values, or a
    # comma separated list of ranges of values.
    # NOTE: THE VALUES HERE ARE EXAMPLES ONLY. REFER TO YOUR MONITOR'S
    # USER MANUAL FOR THE CORRECT NUMBERS.
    VertRefresh 50-160
    EndSection
    # Graphics device section
    # Any number of graphics device sections may be present
    # Standard VGA Device:
    Section "Device"
    Identifier "Standard VGA"
    VendorName "Unknown"
    BoardName "Unknown"
    # The chipset line is optional in most cases. It can be used to override
    # the driver's chipset detection, and should not normally be specified.
    # Chipset "generic"
    # The Driver line must be present. When using run-time loadable driver
    # modules, this line instructs the server to load the specified driver
    # module. Even when not using loadable driver modules, this line
    # indicates which driver should interpret the information in this section.
    Driver "vga"
    # The BusID line is used to specify which of possibly multiple devices
    # this section is intended for. When this line isn't present, a device
    # section can only match up with the primary video device. For PCI
    # devices a line like the following could be used. This line should not
    # normally be included unless there is more than one video device
    # intalled.
    # BusID "PCI:0:10:0"
    # VideoRam 256
    # Clocks 25.2 28.3
    EndSection
    # Device configured by xorgconfig:
    Section "Device"
    Identifier "Card0"
    Driver "nvidia"
    VendorName "All"
    BoardName "All"
    #VideoRam 32768
    # Insert Clocks lines here if appropriate
    EndSection
    # Screen sections
    # Any number of screen sections may be present. Each describes
    # the configuration of a single screen. A single specific screen section
    # may be specified from the X server command line with the "-screen"
    # option.
    Section "Screen"
    Identifier "Screen 1"
    Device "Card0"
    Monitor "Monitor0"
    DefaultDepth 24
    Subsection "Display"
    Depth 8
    Modes "1280x1024" "1024x768" "800x600" "640x480"
    ViewPort 0 0
    EndSubsection
    Subsection "Display"
    Depth 16
    Modes "1280x1024" "1024x768" "800x600" "640x480"
    ViewPort 0 0
    EndSubsection
    Subsection "Display"
    Depth 24
    Modes "1280x1024" "1024x768" "800x600" "640x480"
    ViewPort 0 0
    EndSubsection
    EndSection
    # ServerLayout sections.
    # Any number of ServerLayout sections may be present. Each describes
    # the way multiple screens are organised. A specific ServerLayout
    # section may be specified from the X server command line with the
    # "-layout" option. In the absence of this, the first section is used.
    # When now ServerLayout section is present, the first Screen section
    # is used alone.
    Section "ServerLayout"
    # The Identifier line must be present
    Identifier "Simple Layout"
    # Each Screen line specifies a Screen section name, and optionally
    # the relative position of other screens. The four names after
    # primary screen name are the screens to the top, bottom, left and right
    # of the primary screen. In this example, screen 2 is located to the
    # right of screen 1.
    Screen "Screen 1"
    # Each InputDevice line specifies an InputDevice section name and
    # optionally some options to specify the way the device is to be
    # used. Those options include "CorePointer", "CoreKeyboard" and
    # "SendCoreEvents".
    InputDevice "Mouse1" "CorePointer"
    InputDevice "Keyboard1" "CoreKeyboard"
    EndSection
    # Section "DRI"
    # Mode 0666
    # EndSection

  • Gridbag layout positions

    Hello, I am creating a gui with various swing objects. I put a grouping of various objects within some panels as to allow for simpler layout. The problem however is spaning a jpanel over 2 rows.
    basically i want one panel on the left that spans 2 rows, and two panels that span one row each but are placed horizontally to the first panel. followed by 3 panels places horizontally on a 3rd row. when i try to set gridheigh=2 i get weirdness
    package javaiq3; 
    /** Iq3GUI.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Iq3GUI extends JFrame implements ActionListener{
    /* main window essential objects */
      protected JFrame frame;  // main window
      private JPanel panel;  // content panel for main window
      private GridBagLayout gridbag = new GridBagLayout(); // layout object for main window
       * constructor
       * @param title Main window title
      public Iq3GUI(String title){
        //initializes the main window, its layout and panels
        frame = new JFrame(title); // initializes main window
        frame.addWindowListener(new WindowAdapter() { // window listener
          // exits program when window is closed
          public void windowClosing(WindowEvent e) {System.exit(0);}
        GridBagConstraints c = new GridBagConstraints(); // constraints
        GridBagConstraints subc = new GridBagConstraints(); // constraints
        panel = new JPanel();
        panel.setLayout(gridbag);
        setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    /**** menu bar ****/
        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);
        JMenu menu = new JMenu("File");
        menu.setMnemonic(KeyEvent.VK_F);
        menu.getAccessibleContext().setAccessibleDescription("File menu");
        menuBar.add(menu);
    /**** end: menu bar ****/
    /**** type radio buttons ****/
        JRadioButton[] typeRButton = new JRadioButton[2];
        typeRButton[0]=new JRadioButton("Life");
        typeRButton[1]=new JRadioButton("Crit");
        JPanel typeRButtonPanel = new JPanel(); // panel for radio buttons
        typeRButtonPanel.setLayout(new BorderLayout());
        typeRButtonPanel.setBorder(BorderFactory.createTitledBorder("Type:")); // sets border
        ButtonGroup typeGroup = new ButtonGroup(); // radio button group
        for(int x=0;x<typeRButton.length;x++){ // groups radio buttons together
            typeGroup.add(typeRButton[x]);
        typeRButtonPanel.add(typeRButton[0],BorderLayout.CENTER); // adds them to panel
        typeRButtonPanel.add(typeRButton[1],BorderLayout.SOUTH);
        c.insets = new Insets(15,15,0,0);
        c.gridx=0; c.gridy=0; c.ipady=0; c.gridwidth=1; gridbag.setConstraints(typeRButtonPanel, c);
        panel.add(typeRButtonPanel); // adds radio button panel to main panel
    /**** end: type radio buttons ****/
    /**** company combo box ****/
        JComboBox companyComboBox = new JComboBox();
        JPanel companyComboBoxPanel = new JPanel();
        companyComboBox.setPreferredSize(new Dimension(300,18));
        companyComboBoxPanel.setLayout(gridbag);
        subc.insets = new Insets(-2,5,2,5); gridbag.setConstraints(companyComboBox, subc);
        companyComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Company:"));
        companyComboBoxPanel.add(companyComboBox);
        c.insets = new Insets(0,0,0,0);
        c.gridx=1; c.gridy=0; c.ipadx=0; gridbag.setConstraints(companyComboBoxPanel, c);
        panel.add(companyComboBoxPanel);
    /****  end: company combo box ****/
    /**** product combo box ****/
        JComboBox productComboBox = new JComboBox();
        JPanel productComboBoxPanel = new JPanel();
        productComboBox.setPreferredSize(new Dimension(300,18));
        productComboBoxPanel.setLayout(gridbag);
        subc.insets = new Insets(-2,5,2,5); gridbag.setConstraints(productComboBox, subc);
        productComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Product:"));
        productComboBoxPanel.add(productComboBox);
        c.insets = new Insets(0,0,0,0);
        c.gridx=1; c.gridy=2; c.ipady=0; gridbag.setConstraints(productComboBoxPanel, c);
        panel.add(productComboBoxPanel);
    /****  end: product combo box ****/
    /**** type sex radio buttons ****/
        JRadioButton[] sexRButton = new JRadioButton[2];
        sexRButton[0]=new JRadioButton("Male");
        sexRButton[1]=new JRadioButton("Female");
        JPanel sexRButtonPanel = new JPanel(); // panel for radio buttons
        sexRButtonPanel.setLayout(new BorderLayout());
        sexRButtonPanel.setBorder(BorderFactory.createTitledBorder("Sex:")); // sets border
        ButtonGroup sexGroup = new ButtonGroup(); // radio button group
        for(int x=0;x<sexRButton.length;x++){ // groups radio buttons together
            sexGroup.add(sexRButton[x]);
         sexRButtonPanel.add(sexRButton[0],BorderLayout.CENTER); // adds them to panel
         sexRButtonPanel.add(sexRButton[1],BorderLayout.SOUTH);
         c.gridx=0; c.gridy=3; c.ipady=0; gridbag.setConstraints(sexRButtonPanel, c);
         panel.add(sexRButtonPanel); // adds radio button panel to main panel
    /**** end: sex radio buttons ****/
    /**** smoker check box/combo box ****/
        JCheckBox smokerRButton = new JCheckBox("No");
        JComboBox smokerComboBox = new JComboBox();
        smokerComboBox.setPreferredSize(new Dimension(100,18));
        JPanel smokerPanel = new JPanel();
        smokerPanel.setLayout(new BorderLayout());
        smokerPanel.setBorder(BorderFactory.createTitledBorder("Smoker:"));
        smokerPanel.add(smokerRButton,BorderLayout.CENTER);
        smokerPanel.add(smokerComboBox,BorderLayout.SOUTH);
        c.gridx=1; c.gridy=3; c.ipady=0; gridbag.setConstraints(smokerPanel, c);
        panel.add(smokerPanel);
    /**** end: smoker check box/combo box ****/  
    /**** waiver radio buttons ****/
        JRadioButton[] waiverRButton = new JRadioButton[2];
        waiverRButton[0]=new JRadioButton("Yes");
        waiverRButton[1]=new JRadioButton("No");
        JPanel waiverRButtonPanel = new JPanel(); // panel for radio buttons
        waiverRButtonPanel.setLayout(new BorderLayout());
        waiverRButtonPanel.setBorder(BorderFactory.createTitledBorder("Waiver:")); // sets border
        ButtonGroup waiverGroup = new ButtonGroup(); // radio button group
        for(int x=0;x<waiverRButton.length;x++){ // groups radio buttons together
            waiverGroup.add(waiverRButton[x]);
         waiverRButtonPanel.add(waiverRButton[0],BorderLayout.CENTER); // adds them to panel
         waiverRButtonPanel.add(waiverRButton[1],BorderLayout.SOUTH);
         c.gridx=2; c.gridy=3; c.ipady=0; gridbag.setConstraints(waiverRButtonPanel, c);
         panel.add(waiverRButtonPanel); // adds radio button panel to main panel
    /**** end: type radio buttons ****/
    /**** main gui properties ****/
      // Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); //screen dimensions
      //  Rectangle frameDim = frame.getBounds(); // frame boundries
      //  frame.setLocation((screenDim.width - frameDim.width) / 4,(screenDim.height - frameDim.height) / 4);//sets frame's location to center screen
      //  frame.setSize(600,100);
        frame.setContentPane(panel); frame.pack();
        frame.setVisible(true);
    /**** end: main gui properties ****/
       * setLookAndFeel
       * Sets the look and feel of the application, if it cannot be set to the
       * user defined one, sets the default java
       * @param feel Stores the look and feel string
      public void setLookAndFeel(String feel){
         try { // sets the GUI style to the parameter type
              UIManager.setLookAndFeel(feel);
          } catch (Exception e) {
             try{
               UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
             catch (Exception e2){ // if default java one cannot be set, exits program
                System.err.println(e2.getMessage());
                System.exit(0);
       * errorBox
       * Displays a JDialog box with an ok button, programmer defined message
       * and a warning icon
       * @param message Programmer defined message
      public void errorBox(String message){
        JOptionPane.showMessageDialog(frame,message,"Error",JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    * actionPerformed
    * Performs action sent to by action listener
    * @param e Action object
      public void actionPerformed(ActionEvent e){
        System.out.println("Click");
    * Main
    * Test method
    * @param args Does nothing
    public static void main(String[] args){
        Iq3GUI heh = new Iq3GUI("IQ3");
    }

    Wow. That's some ugly code. You might want to work on coding conventions a bit.
    The reason books provide information in paragraphs is to give the eye a rest and the brain time to process the information (a brain is only 8 MHz -- no kidding). Your code should do the same. If 80% of effort goes into maintaining code, you'll help yourself (and potential coworkers) by coding neatly so that things are easy to understand at a glance without dealing with a lot of visual clutter.
    1) Try to put comments on their own lines instead of whacking them onto the end of a line of code.
    2) Include spaces between code segments that are related tasks -- think of them as "virtual blocks" (since they're not enclosed in braces). Think about the paragraph analogy again. A paragraph groups related sentences. Let your code do the same.
    3) Never, ever jam multiple statements into a single line of code. It's a huge pain in the ass to read. While the compiler doesn't care about whitespace, human beings do.
    4) When working with GridBagLayout, add all your components in the same part of your class file. By doing so, when you need to alter the layout, you don't have to dig through all of your code to find bits and pieces of the layout. Your project is small, but if you do this stuff for a living, you're eventually going to work on gigantic projects. My current project, for example, consists of 20,000 lines of code just for the GUI (and my project isn't even all at big).
    5) Exiting a program without telling the user is laaaaame. I know you're just playing around, but now's the time to get good habits.
    OK, so now that you've sat through the editorial, the quick and dirty answer is that you have to explicitly specify widths and heights in your constrains for each component, otherwise GridBagLayout's behavior becomes hard to predict.
    In your code, you specify gridwidth once and never again. You know that a Constraint object is reusable, right? What you've just told GridBagLayout is "try to make everything the same width." Meanwhile, the layout is trying to respect your preferred sizes.
    Please read the Java Tutorial on GridBagLayout, particularly the suggestion to sketch your layout on a piece of paper ahead of time so that you remember which constraint attributes to change. For safe measure, you might want to specify an entire set of constraints each time you lay out a component so that you won't leave out something important.
    As for the background color, I just fixed it by setting a background for your main panel. Windows look and feel is lame, I guess. I always use the Java look and feel, so I haven't run into your problem before.
    See my modified code below.
    //package javaiq3; 
    /** Iq3GUI.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Iq3GUI extends JFrame implements ActionListener
        protected JFrame frame;
        private JPanel panel;
        private GridBagLayout gridbag = new GridBagLayout();
        public Iq3GUI(String title)
            frame = new JFrame(title);
            frame.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            GridBagConstraints c = new GridBagConstraints();
            GridBagConstraints subc = new GridBagConstraints();
            panel = new JPanel();
            panel.setLayout(gridbag);
            panel.setBackground(Color.lightGray);
            setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            JMenuBar menuBar = new JMenuBar();
            frame.setJMenuBar(menuBar);
            JMenu menu = new JMenu("File");
            menu.setMnemonic(KeyEvent.VK_F);
            menu.getAccessibleContext().setAccessibleDescription("File menu");
            menuBar.add(menu);
            JRadioButton[] typeRButton = new JRadioButton[2];
            typeRButton[0]=new JRadioButton("Life");
            typeRButton[1]=new JRadioButton("Crit");
            JPanel typeRButtonPanel = new JPanel();
            typeRButtonPanel.setLayout(new BorderLayout());
            typeRButtonPanel.setBorder(BorderFactory.createTitledBorder("Type:"));
            ButtonGroup typeGroup = new ButtonGroup();
            for(int x=0;x<typeRButton.length;x++)
                typeGroup.add(typeRButton[x]);
            typeRButtonPanel.add(typeRButton[0],BorderLayout.CENTER);
            typeRButtonPanel.add(typeRButton[1],BorderLayout.SOUTH);
            c.insets = new Insets(15,15,0,0);
            c.gridx=0;
            c.gridy=0;
            c.ipady=0;
            c.gridwidth=1;
            gridbag.setConstraints(typeRButtonPanel,c);
            panel.add(typeRButtonPanel);
            JComboBox companyComboBox = new JComboBox();
            JPanel companyComboBoxPanel = new JPanel();
            companyComboBox.setPreferredSize(new Dimension(300,18));
            companyComboBoxPanel.setLayout(gridbag);
            subc.insets = new Insets(-2,5,2,5);
            gridbag.setConstraints(companyComboBox, subc);
            companyComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Company:"));
            companyComboBoxPanel.add(companyComboBox);
            c.insets = new Insets(0,0,0,0);
            c.gridx=1;
            c.gridy=0;
            c.ipadx=0;
            gridbag.setConstraints(companyComboBoxPanel, c);
            panel.add(companyComboBoxPanel);
            JComboBox productComboBox = new JComboBox();
            JPanel productComboBoxPanel = new JPanel();
            productComboBox.setPreferredSize(new Dimension(300,18));
            productComboBoxPanel.setLayout(gridbag);
            subc.insets = new Insets(-2,5,2,5);
            gridbag.setConstraints(productComboBox, subc);
            productComboBoxPanel.setBorder(BorderFactory.createTitledBorder("Product:"));
            productComboBoxPanel.add(productComboBox);
            c.insets = new Insets(0,0,0,0);
            c.gridx=1; c.gridy=2; c.ipady=0;
            gridbag.setConstraints(productComboBoxPanel, c);
            panel.add(productComboBoxPanel);
            JRadioButton[] sexRButton = new JRadioButton[2];
            sexRButton[0]=new JRadioButton("Male");
            sexRButton[1]=new JRadioButton("Female");
            JPanel sexRButtonPanel = new JPanel();
            sexRButtonPanel.setLayout(new BorderLayout());
            sexRButtonPanel.setBorder(BorderFactory.createTitledBorder("Sex:"));
            ButtonGroup sexGroup = new ButtonGroup();
            for(int x=0;x<sexRButton.length;x++)
                sexGroup.add(sexRButton[x]);
            sexRButtonPanel.add(sexRButton[0],BorderLayout.CENTER);
            sexRButtonPanel.add(sexRButton[1],BorderLayout.SOUTH);
            c.gridx=0;
            c.gridy=3;
            c.ipady=0;
            gridbag.setConstraints(sexRButtonPanel,c);
            panel.add(sexRButtonPanel);
            JCheckBox smokerRButton = new JCheckBox("No");
            JComboBox smokerComboBox = new JComboBox();
            smokerComboBox.setPreferredSize(new Dimension(100,18));
            JPanel smokerPanel = new JPanel();
            smokerPanel.setLayout(new BorderLayout());
            smokerPanel.setBorder(BorderFactory.createTitledBorder("Smoker:"));
            smokerPanel.add(smokerRButton,BorderLayout.CENTER);
            smokerPanel.add(smokerComboBox,BorderLayout.SOUTH);
            c.gridx=1;
            c.gridy=3;
            c.ipady=0;
            gridbag.setConstraints(smokerPanel,c);
            panel.add(smokerPanel);
            JRadioButton[] waiverRButton = new JRadioButton[2];
            waiverRButton[0]=new JRadioButton("Yes");
            waiverRButton[1]=new JRadioButton("No");
            JPanel waiverRButtonPanel = new JPanel();
            waiverRButtonPanel.setLayout(new BorderLayout());
            waiverRButtonPanel.setBorder(BorderFactory.createTitledBorder("Waiver:"));
            ButtonGroup waiverGroup = new ButtonGroup();
            for(int x=0;x<waiverRButton.length;x++)
                waiverGroup.add(waiverRButton[x]);
            waiverRButtonPanel.add(waiverRButton[0],BorderLayout.CENTER);
            waiverRButtonPanel.add(waiverRButton[1],BorderLayout.SOUTH);
            c.gridx=2;
            c.gridy=3;
            c.ipady=0;
            gridbag.setConstraints(waiverRButtonPanel,c);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.gridheight = 2;
            //c.weightx = 100;
            //c.weighty = 100;
            c.insets = new Insets(0,0,0,0);
            panel.add(typeRButtonPanel, c);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = 0;
            c.gridwidth = 2;
            c.gridheight = 1;
            //c.weightx = 100;
            //c.weighty = 100;
            c.insets = new Insets(0,0,0,0);
            panel.add(companyComboBoxPanel, c);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = 1;
            c.gridwidth = 2;
            c.gridheight = 1;
            //c.weightx = 100;
            //c.weighty = 100;
            c.insets = new Insets(0,0,0,0);
            panel.add(productComboBoxPanel, c);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 0;
            c.gridy = 3;
            c.gridwidth = 1;
            c.gridheight = 2;
            //c.weightx = 100;
            //c.weighty = 100;
            c.insets = new Insets(0,0,0,0);
            panel.add(sexRButtonPanel, c);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = 3;
            c.gridwidth = 1;
            c.gridheight = 2;
            //c.weightx = 100;
            //c.weighty = 100;
            c.insets = new Insets(0,0,0,0);
            panel.add(smokerPanel, c);
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 2;
            c.gridy = 3;
            c.gridwidth = 1;
            c.gridheight = 2;
            //c.weightx = 100;
            //c.weighty = 100;
            c.insets = new Insets(0,0,0,0);
            panel.add(waiverRButtonPanel, c);
            frame.setContentPane(panel);
            frame.pack();
            frame.setVisible(true);
        public void setLookAndFeel(String feel)
            try
                UIManager.setLookAndFeel(feel);
            catch(Exception e)
                try
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                catch(Exception e2)
                    System.err.println(e2.getMessage());
                    System.exit(0);
        public void errorBox(String message)
            JOptionPane.showMessageDialog(frame,message,"Error",JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        public void actionPerformed(ActionEvent e)
            System.out.println("Click");
        public static void main(String[] args)
            Iq3GUI heh = new Iq3GUI("IQ3");
    }

  • Gridbag layout continues to confound me...

    I am having problems with the gridx and gridy constraints when trying to use gridbag layout. They seem to have no effect when I use them. The button always appears in the top left of the panel. Other constraints seem to work as expected.
    For example: c2.fill = GridBagConstraints.BOTH; will fill up the entire panel with my button.
    Any advice on what I am doing wrong this time?
    Thanks
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Question
         public JPanel test()
              JPanel testPanel = new JPanel(new GridBagLayout());
              GridBagConstraints c2 = new GridBagConstraints();
              c2.insets = new Insets(5,5,5,5);
              c2.weightx = 1.0;
              c2.weighty = 1.0;
              c2.anchor = c2.NORTHWEST;
              JButton redButton = new JButton("Button");
              c2.gridx = 2;
              c2.gridy = 2;
              //c2.fill = GridBagConstraints.BOTH;//this works as expected
              testPanel.add(redButton,c2);
              return testPanel;
         public Container createContentPane()
              //Create the content-pane-to-be.
              JPanel contentPane = new JPanel(new BorderLayout());
              contentPane.setOpaque(true);
              return contentPane;
         private static void createAndShowGUI()
              //Create and set up the window.
              JFrame frame = new JFrame("question");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              Question demo = new Question();
              frame.setContentPane(demo.createContentPane());
              frame.add(demo.test());
              //Display the window.
              frame.setSize(400, 400);
              frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
        }//end main
    }//end Question

    GridBagLayout keeps zero width/height grid for non-existant component for the grid.
    You could override this behavior by using GBL's four arrays as shown below.
    However, in order to get the desired layout effect, using other layout manager, e.g. BoxLayout and/or Box, is much easier and flexible as camickr, a GBL hater, suggests.
    Anyway, however, before using a complex API class as GBL, you shoud read the documentation closely.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Question{
      // you may adjust these values for your taste
      static final int rowHeight    = 100;
      static final int colWidth     = 100;
      static final double rowWeight = 1.0;
      static final double colWeight = 1.0;
      public JPanel test(){
        GridBagLayout gb = new GridBagLayout();
        gb = keepAllRowsAndColumns(gb, 3, 3);
        JPanel testPanel = new JPanel(gb);
        GridBagConstraints c2 = new GridBagConstraints();
        c2.insets = new Insets(5,5,5,5);
        c2.weightx = 1.0;
        c2.weighty = 1.0;
        c2.anchor = c2.NORTHWEST;
        JButton redButton = new JButton("Button");
        c2.gridx = 2;
        c2.gridy = 2;
        // c2.fill = GridBagConstraints.BOTH;//this works as expected
        testPanel.add(redButton,c2);
        return testPanel;
      GridBagLayout keepAllRowsAndColumns(GridBagLayout g, int rn, int cn){
        g.rowHeights = new int[rn];
        g.columnWidths = new int[cn];
        g.rowWeights = new double[rn];
        g.columnWeights = new double[cn];
        for (int i = 0; i < rn; ++i){
          g.rowHeights[i] = rowHeight;
          g.rowWeights[i] = rowWeight;
        for (int i = 0; i < cn; ++i){
          g.columnWidths[i] = colWidth;
          g.columnWeights[i] = colWeight;
        return g;
      private static void createAndShowGUI(){
        JFrame frame = new JFrame("question");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Question demo = new Question();
        frame.getContentPane().add(demo.test(), BorderLayout.CENTER);
        frame.setSize(400, 400);
        frame.setVisible(true);
      public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            createAndShowGUI();
    }

  • Gridbag Layout and Tabbed Panes

    First off, I'm pretty new to Java, I started it around February as a school course, and it's been a pretty smooth ride. Recently, we started to code GUI, trying out different layouts and whatnot. I'm having a little trouble in this portion as our teacher did not really delve into it very much. My question concerns the GridBag layout within a panel of a tab (sorry if this is unclear, I'm talking about something that looks like this: http://www.codeproject.com/useritems/tabcontrol.asp). I don't know how to use GridBag constraints within a panel. What I used to do with GridBag was simply use some code that looked like (forgive me, this might not be very accurate): AddComponent button1(#, #, #, #) and define what each of those numbers meant later (first would be row, second would be column, third would be width, fourth would be height, for example). But now, with the tabs, each button, label, or any other control would be declared, then I would place a bunch of direct constraints after, like this:
    JButton button1 = new JButton("1");
    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;then add them into the panel like this:
    panel1.add(button1, constraints);However, I have tried making the buttons on top of each other, and other patterns, but it would just place the buttons next to each other within the panel. How do I make it so that the constraints work? Or rather, if they do work, what kinda things might mess it up? I think the problem is that I dunno how to make the constraints specific to that one button.
    Also, how do I make each panel a certain size instead of each panel being as small as possible to contain anything within it.
    I'm sorry if this all sounds very vague, I'd be more than happy to give you any needed information. Also, I'm not asking any of you to do my homework, I just need a little clarification or an example. Just in case, here's the code I'm working on: http://hashasp.mine.nu/paster/?1376. Be aware that there are no comments or anything, it's very bare. Also, the form may be a bit messy because I'm pretty much reusing code that was given to me, just manipulating it in a different way. Thanks a lot in advanced for your time in reading this.

    * GridBag_Demo.java
    import java.awt.*;
    import javax.swing.*;
    public class GridBag_Demo extends JFrame {
        public GridBag_Demo() {
            setTitle("GridBag Demo");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setSize(400,300);
            setLocationRelativeTo(null);
            GridBagConstraints gridBagConstraints;
            jTabbedPane1 = new JTabbedPane();
            jPanel1 = new JPanel();
            jButton1 = new JButton();
            jButton2 = new JButton();
            jButton3 = new JButton();
            jPanel1.setLayout(new GridBagLayout());
            jButton1.setText("jButton1");
            gridBagConstraints = new GridBagConstraints();
            gridBagConstraints.insets = new Insets(2,2,2,2);
            jPanel1.add(jButton1, gridBagConstraints);
            jButton2.setText("jButton2");
            gridBagConstraints.gridy = 1;
            jPanel1.add(jButton2, gridBagConstraints);
            jButton3.setText("jButton3");
            gridBagConstraints.gridy = 2;
            jPanel1.add(jButton3, gridBagConstraints);
            jTabbedPane1.addTab("tab1", jPanel1);
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
        public static void main(String args[]) {
            new GridBag_Demo().setVisible(true);
        private JButton jButton1;
        private JButton jButton2;
        private JButton jButton3;
        private JPanel jPanel1;
        private JTabbedPane jTabbedPane1;
    }

Maybe you are looking for