GridBag in a GridBag

Hi there, having a spot of trouble with layouts.
I'm very new to Swing, but I've done a bit of poking around and it seems the easiest way to set things exactly where I want them is in a GridBagLayout.
I have a slight problem though, I have one column with three rows that must be the same height as a column with four rows. Now, I know I can't span 1.3 rows, so I'm attempting to put two JPanels (with GridBagLayout) side by side. This way I can resize the left panel (with three rows) to be the same size as the right panel (with four) then weight the two evenly.
Now eventually I'll have 24 pairs of right and left panels, the right panel being much longer horizontally than the left. I'd like to be able to display them in a scrolling panel in 2 columns, 24 rows. Thus I'm also attempting to place a GridBag within a GridBag.
When I try to put it into action, the problem I have is that the left and right panels (which are GridBags) get 'flattened' - their rows are layed out end to end to make one long row. I've tried switching the host (eventually a scrolling panel, at the moment it's the content pane of a JFrame) panel to Border and Flow layouts, with the same effects. I've tried setting the ipad constraints on the left and right panels (not their contents) to no effect.
Does anyone have any suggestions that might help?
My thanks!
Nick.

I think you should use two panels whit a grid layout instead of a gridBagLayout, and put them in another panel whit also a gridlayout with 2 columns :
For example :
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,2)); // 2 columns and 1 row
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(3,1)); // 1 column and 3 rows
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new GridLayout(4,1)); // 1 column and 4 rows
panel.add(leftPanel);
panel.add(rightPanel);This assumes that leftPanel and rightPanel have the same size.
And now for the global panel with 24 sub-panels, you can do the same thing :
JPanel globalPanel = new JPanel();
globalPanel.setLayout(new GridLayout(24,2));
globalPanel.add(leftPanel1);
globalPanel.add(rightPanel1);
globalPanel.add(leftPanel24);
globalPanel.add(rightPanel24);
JScrollPane scroller = new JScrollPane(globalPanel);I hope that helps,
Denis

Similar Messages

  • Gridbag inside another gridbag ?

    Hi!
    Is it possible to define a second gridbag inside another one ie a gridbag in another gridbag with different constraints ?

    No, one single GridBagLayout will not do that. Maybe
    any result you desire, but not every result we
    other weird people desire. :)
    For example, Borders can only be put around a whole
    component and not around an arbitrary selection of
    components in a container - gridbag or not. So if I
    want to group components in a large gui with borders,
    then I have to use nested containers. And then it
    sometimes becomes necessary to use GridBagLayout on
    both the outer container and the inner containersAll, I can say is thank <insert diety of choice> I'm not working on your project :-p

  • JTextArea & Gridbag layout - max size of control

    Hello everyone:
    I am currnetly using a JTextArea with the Gridbag layout. I want to limit the size of the JTextArea. Found an article when I did a "search" that says the size is actually controlled by the layout manager. Have tried setMaximunSize(), no luck. It appears the layout manager ignores this. The problem I am having is that I can set the size I want, however if the user types a lot of text in to the JTextArea, the control expands and over and "pushes" the controls below it down. How do I keep the layout manager from allowing this to happen?
    Thanks in advance, Bart

    Hello everyone:
    I am currnetly using a JTextArea with the Gridbag
    layout. I want to limit the size of the JTextArea.
    Found an article when I did a "search" that says the
    size is actually controlled by the layout manager.
    Have tried setMaximunSize(), no luck. It appears the
    layout manager ignores this. The problem I am having
    is that I can set the size I want, however if the user
    types a lot of text in to the JTextArea, the control
    expands and over and "pushes" the controls below it
    down. How do I keep the layout manager from allowing
    this to happen?
    Thanks in advance, Bart Do you wish to allow the user to enter as much text as he or she likes? If so, wrap the JTextArea in a JScrollPane and set the preferred size of the JScrollPange to the area you'd like the pane to consume. It'll listen, no doubt. :)

  • Multiple components in a gridbag layout cell

    Is it possible to have two components in one cell of a grid bag layout? Say, a textfield box and some text to its immediate right? If so, can someone post an example? Thanksmuch.

    Put the textfield and a label with the text in a panel. Then add that panel to your gridbag cell.

  • Gridbag Layout In Flex - Looking for canvasgrid

    Hello,
    I found a posting about a layout mechanism call canvasgrid,
    based on the gridbag layout principle. It is documented at
    Mannu's Blog.
    It is a very effective layout, but the download is broken, and so
    If anyone happens to have his open source reference The source
    filename is canvasgrid_v0.3.1.zip, and it was originally located
    at:
    http://tasmania.globat.com/~mannu.info/flex/canvasgrid_v0.3.1.zip
    If anyone happens to be a code squirel, like myself, and has
    a copy of this, that would be great. I will make it a part of the
    flexlib, just because it's so usefull.
    Thaks

    Hi, You can try this:
    package {
    import flash.display.MovieClip;
    import mx.core.SpriteAsset;
    import mx.core.MovieClipAsset;
    public class GameSymbols extends MovieClip {
    [Embed(source='gameSymbols.swf', symbol='Coffee')]
    private var CoffeeClass:Class;
    //CoffeeClass represents the embedded symbol.
    public function GameSymbols() {
    //Flex defines CoffeClass as a reference to a subclass of
    //SpriteAsset class - for single-frame SWF files or
    //MovieClipAsset class - for multiframe SWF files.
    var myCoffee:SpriteAsset = new CoffeeClass() as SpriteAsset;
    //var myCoffee:MovieClipAsset = new CoffeeClass() as
    MovieClipAsset;
    //You can manipulate the embedded Symbol by using the
    methods
    //and properties of the SpriteAsset or MovieClipAsset class.
    myCoffee.setActualSize(50, 50);
    myCoffee.x = 10;
    myCoffee.y = 10;
    myCoffee.alpha = 100;
    myCoffee.visible = true;
    addChild(myCoffee);
    Luk.

  • 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);
    }

  • GUI - Problem with GridBag

    Hi everyone,
    I have been trying to get this GUI built from the ground up and I have encountered a problem with the GridBag(exception error that the fields being added can not be done. Also, my method main seems to be off track, I have a working program which the display fields have been modified to display object and everything else is the same except that I can not get the GUI to run.
    The following is the code and any suggestions as to what I can do to get this going will be appreciated. Thank you.
    import javax.swing.JLabel; /* displays text and images*/
    import javax.swing.SwingConstants; /* common constants used with Swing*/
    import javax.swing.Icon; /* interface used to manipulate images*/
    import javax.swing.ImageIcon; /* loads images*/
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.PrintStream;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.text.*;     
    import javax.swing.JFrame;/* provides basic window features*/     
    import java.util.Arrays;
    import javax.swing.ImageIcon.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class FinalInventoryGUI extends JFrame
    {//Private variables.
    private GridBagLayout layout = new GridBagLayout();
    private GridBagConstraints constraints = new GridBagConstraints();
    //Private data from main program
    private String productName;
    private String itmeNumber;
    private double unitPrice;
    private int unitStock;
    private double productValue;
    private double inventoryValue;
    private double reStkfee;
    //Declaration of the JLabels.
    private JLabel logoLabel;
    private JLabel productNameLabel;
    private JLabel itemNumberLabel;
    private JLabel unitPriceLabel;
    private JLabel unitStockLabel;
    private JLabel productValueLabel;
    private JLabel InventoryValueLabel;
    private JLabel reStkfeeLabel;
    //Declaration of the text Fields for data Entry.     
    private JTextField productNameText;
    private JTextField itemNumberText;
    private JTextField unitPriceText;
    private JTextField unitStockText;
    private JTextField productValueText;
    private JTextField inventoryValueText;
    private JTextField reStkfeeText;
    private JTextField titleText;
    //Declaration of the JButtons for user interface.
    private JButton first;//To move to first element in the array.
    private JButton next;//To move to next element in the array.
    private JButton previous;//To move to next element in the array.
    private JButton lastButton;//To move to the first element in the array.
    private JButton addButton;//To add a product to the array.
    private JButton modifyButton;//To modify an element in the array.
    private JButton deleteButton;//To remove a product from the array.
    private JButton saveButton;//To save the array elements to C:\.
    private JButton searchButton;//To search for an element in the array.
    private Product products[];//Declaration of array product[] for storing entries.
    private int NumOfProducts;//Declaration of the variable defining the number of products.
    private int Index=0;//Setting the counter index to initiate at "0".
    //Constants
    private final static int LOGO_WIDTH  = 4;
    private final static int LOGO_HEIGHT = 4;
    private final static int LABEL_WIDTH  = 1;
    private final static int LABEL_HEIGHT = 1;
    private final static int TEXT_WIDTH  = LOGO_WIDTH-LABEL_WIDTH;
    private final static int TEXT_HEIGHT = 1;
    private final static int BUTTON_WIDTH  = 1;
    private final static int BUTTON_HEIGHT = 1;
    private final static int LABEL_START_ROW = LABEL_HEIGHT+LABEL_WIDTH+1;
    private final static int LABEL_COLUMN = 0;
    private final static int TEXT_START_ROW = LABEL_START_ROW;
    private final static int TEXT_COLUMN = LABEL_WIDTH+1;
    private final static int BUTTON_START_ROW = LABEL_START_ROW+9*LABEL_HEIGHT;
    private final static int BUTTON_COLUMN = LABEL_COLUMN;
    private final static int SEARCH_START_ROW = BUTTON_START_ROW+3;
    final static String EMPTY_ARRAY_MESSAGE = "Hit ADD to add a new PRODUCT";
    //Constructor-New instance of the JLabelTextFieldView.
    public FinalInventoryGUI( Product productsIn)
        {//Passing the frame title to JFrame, set the IconImage.
             super("Welcome To The Inventory Program");
             setLayout(layout);
             //Copy the input array(products).
             setProduct(productsIn);//maybe the title?????
             //Start the display with the first element of the array.
             index = 0;
             //Build the GUI
             buildGUI();
             //Values
             updateAllTextFields();
             }//End of the constructor for building the GUI.
             //Methods for copying the input of Product array to the GUIs private array
             //variable
             private void setInventoryArray(Product productsIn[])
                  products = new Product[productIn.length];
                  for (int i = 0; i<products.length; i++)
                  {//Creates A Product array element from the input array.
                       prodcuts[i] = new Product(productIn);
                   products[i] = new Product(productIn[i].productName(), productIn[i].itemNumber(),
                                                      productIn[i].unitStock(), productIn[i].unitPrice());
              //System prints out a ineof the productsIn array to a string.
         }//End of the for statment.
         }//End for copying the array.
         //A method for updating each of the GUIs fields.
         private void updateAllTextFields()
              if(products.length > 0)//Then update the JTextField display.
              {// Update the product name text field.
              productNameText.setText(products[index].productName());
              //Update the Update the itemNumber text field.
              itemNumberText.set(String.format("%d", products[index].itemNumber()));
              //Update the title text field.
              titleText.setText(dvd[index].title());
              //Update the unitStock text field.
              unitStockText.setText(String.format("%d",products[index].unitStock()));
              //Update the unit price textField.
              unitPriceText.setText(String.format("$%.2f",products[index].unitPrice()));
              //Update the productValue textField.
              productValueText.setText(String.format("$%.2f", products[index].productValue()));
              //Update the restocking fee text field.
              reStkfeeText.setText(String.format("$%.2f",reStkfee()));
              //Update the total value of the inventory text field.
              inventoryValueText.setText(String.formtat("$%.2f",Product.productValue(products)));
              }//End of the if statement.
              else//Put a special message in the fields.
              {//Update the productName textField.
              productNameText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the itemNumber textField
              itemNumberText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the title textField.
              titleText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the units in stock textField.
              unitStockText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the unitPrice textFied.
              unitPriceText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the productValue textField.
              productValueText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the restocking fee textField.
              reStkfeeText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the totatl inventoryValue textField.
              inventoryValueText.setText(EMPTY_ARRAY_MESSAGE);
              }//End else
         }//Set the appropriate fields editable or uneditable.
         private void setModifiableTextFieldsEnabled(Boolean state)
         {//The fields of the product name, item number, unit price,
         // and stock can be editable or non editable.
         itemNumber.setEditable(state);
         productName.setEditable(state);
         unitPrice.setEditable(state);
         unitStock.setEditable(state);
         }//End setting of the modifiable textFields.
         //Methods for the JButton methods.
         private class ButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
              {//This is the first button being pressed by the user.
                   if(event.getSource()==firstButton)
                        handleFirstButton();
                   }//End if
                   else if(event.getSource()==previousButton)//Button previous is pressed by user.
                        handlePreviousButton();
                   }//End else if
                   else if (event.getSource()==nextButton)//Button next is pressed by user.
                        handleNextButton();
                   }//End else if.
                   else if (event.getSource()==lastButton)//Button last is pressed by the user.
                        handleLastButton();
                   }//End else if.
                   else if(event.getSource()==firstButton)
                        handleFirstButton();
                   }//End else if.
         }//End metod of actionPeformed.
         }//End class ButtonHandler
         //Displaying the first element of the Product array
         private void handlerFirstButton()
         {//Setting the index to the first element in the array.
              index = 0;
         //Update and disable modification
         updateAllFields();
         setModifiableTextFieldsEnabled(false);
         }//End method for handling the first button.
         //Displaying the next element of the products array or wrap to the first.
         private void handleNextButton()
         {//Incrementation of the index.
         index++;
         //If the index exceeds the last valid array element, wrap around to the first
         //element of the array.
         if(index > products.length-1)
              index = 0;
         }//End if statment.
         //Update and disable the modification.
         updateAllFields();
         setModifiableTextFieldsEnabled(false);
         }//End method of handleNextButton.     
         private void handlePreviousButton()
              index--;
              if(index < 0)
                   index = products.length -1;
              }//End if statment.
              //Update and disabe modification.
              updateAllTextFields();
              setModifiableTextFieldsEnabled(false);
         }//End method of handlePreviousButton.
         private void handleLastButton()
              index--;
              if(index < products.length -1)
                   index = 2;
              }//End if statment.
              updateAllTextFields();
              setMdifiableTextFieldsEnabled(false);
              }//End method for handleLatButton
         //The textFieldHandler class - handling the events of the buttonsmethods
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
              {//The user pressed "ENTER" in the JTextField "title" text.
              if(event.getSource() == itemNumber)
                   //HandleItemNumberTextField()is fired.
              }//End the if statement.
              //The user pressed "ENTER" in the JTextField "title" text.
              else if (event.getSource() == titleText)
                   //HandleTitleTextField() is fired.
              }//End the if statement.
         //The user pressed "ENTER" in the JTextField "unitStoc" text.
              else if(event.getSource() == unitStockText)
                   //HandleUnitStockTextField() is fired.
              }//End the if statment
              //The user pressed "ENTER" in the JtextField "unitPrice" text.
              else if (event.getSource() == unitPriceText)
                   //HandleUnitPriceTextField() is fired.
              }//End the if statment.
         //The user pressed "ENTER" in the JTextField "Search" text.
         else if(event.getSource() == searchText)
              //HandleSearchTextField() is fired.
         }//End the if statment.
              }//End the method actionPerformed.
         }//End the inner class TextFieldhandler.
              //The GUI methods.
              //Building the GUI.
              private void BuildGUI()
              {//Mthod for adding the LOGO.
              buildLogo();
              //Add the text fields and their labels.
              buildLabels();
              buildTextFields();
              //Add the navigation and other buttons.
              buildMainButtons();
              //Provide value to the Fields.
              updateAllTextFields();
              //provide some setup to the frame.
                        setSize(FRAME_LENGTH, FRAME_WIDTH);
                        setLocation(FRAME-XLOC, FRAME_YLOC);
                        setResizable(false);
                        //PACK(); IS THIS NOT PART OF THE GUI ADDED AT THE END OR IS WHAT
                        //FOLLOWS THE SAME AS SAYING ".PACK()".
                        setDefaultCloseOperation(EXIT_ON_CLOSE);//DOES IT MATTER WHERE THIS LINE FALLS?
                        //WHEN I TRIED TO USE IT IN THE MAIN I RECEIVED AN ERROR AND THE SAME WHEN I
                        //PLACED IT IN THE CONSTRUCTOR--WHY?.
                        setVisible(true);
              }//End of building the GUI.
              //Addin the LOGO to the Frame.
              private void buildLogo()
                   constraints.weightx = 2;
                   constraints.weigthy = 1;
                   logoLabel = new JLabel(new ImageIcon("O2K.jpg"));
                   logoLabel.setText("Products Inventory");
                   constraints.fill = GridBagConstraints.BOTH;
                   addToGridbag(logoLabel,2,2,LOGO_WIDTH, LOGO_HEIGHT);
                   //Creating a vertical space.
                   addToGridBag(new JLabel(""),LOGO_HEIGHT+1,0, LOGO_WIDTH, LABEL_WIDTH);
              }//End the method with building the LOGO.
                   //Build the panel just containing the text.
                   private void buildLabels()
                   {//Set up if for readability).
                   int rows = 0;
                   int column = 0;
                   int width = 0;
                   int height = 0;
              column = LABEL_COLUMN;
              width = LABEL_WIDTH;
              height = LABEL_HEIGHT;
                   constraints.weightx = 1;
                   constraints.weighty = 0;
                        constraints.fill = GridbagConstraints.Both;
                        //Create the name labes and name the TextFields.
                        productNameLabel = new JLabel("Product Name:");
                        productnamelabel.setLabelfor(productNameField);
                        productNameLabel.setLabelFor(productNameText);
                        productNameLabel.setToolTipText("Enter The Product Name Here");
                        row = Label_START_ROW;          
                        addToGridBag(productNameLabel, row, column, width, height);
                        //Create the itemNumberLabel and TextField.
                        itemNumberLabel = new JLabel("Product Id:");
                        itemNumberLabel.setLabelFor(itemNumberText);
                        row += LABEL_HEIGHT;
                        addToGridBag(itemNumber, row, column, width, height);
                        //Create the title label for the Product and the title text field.
                        titleLabel = new JLabel("Inventory Of Products:");
                        titleLabel.setLabelFor(titleText);
                        row += LABEL_HEIGHT;
                        addToGridBag(titleLabel,row,column,width,height);
                        //Create the unitStock label and textField.
                        unitStockLabel = new JLabel("Units In Stock:");
                        unitStockLabel.setLabelFor(unitStockLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(unitStocklabel, row, column, height);
                        //Creat the unitPrice label and textField.
                        unitPriceLabel = new JLabel("Unit Price");
                        unitPriceLabel.setLabelFor(unitPriceLabel);
                        unitPriceLabel.setToolTipText("The Cost Of The Product");
                        row += LABEL_HEIGHT;
                        addToGridBag(unitPriceLabel, row, column, height);
                        //Create the productValue label and textField.
                        productValueLabel = new JLabel("Total Product Value:");          
                        productValueLabel.setLabelFor(productValueLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(productValue, row, column, height);
                        //Create the restocking fee of 1.05% Label and textField.
                        reStkfeeLabel = new JLabel("Product Restock Fee:");
                        reStkfeeLabel.setLabelFor(reStkfeeLabel);
                        row+= LABEL_HEIGHT;
                        addToGridBag(reStkfee, row, column, height);
                        //Create a vertical space.
                        row += LABEL_HEIGHT;
                        //Create the Total Inventory Value label and textField.
                        inventoryValueLabel = new JLabel("Total Inventory Value:");
                        inventoryValueLabel.setLabelFor(inventoryValueLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(inventoryValue, row, column, height);
              }//End the method for building the labels
                        //Build the methods for the TextFields.
                        private void buildTextFields()
                             {//Defining the variables
                             int row = 0;
                             int column = 0;
                             int width = 0;
                             int height = 0;
                             column = TEXT_COLUMN;
                             width = TEXT_WIDTH;
                             height = TEXT_HEIGHT;
                             constraints.fill = GridBagConstraints.BOTH;
                             constraints.weightx = 1;                    
                             TextFieldHandler handler = new TextFieldHandler();
                             productNameText = new JTextField("Product Name");
                             productNameText.setEditable(false);
                             row = TEXT_START_ROW;
                             addToGridBag(productNameText, row, column, height);
                        itemNumberText = new JTextField("Product Id");
                        itemNumberText.setEditable(false);
                        row = TEXT_START_ROW;
                        addToGridBag(itemNumberText, row, column, height);
                        titleText = new JTextField("Title");
                        titleText.addActionListener(handler);
                        titleText.setEditable(false);
                        row += TEXT_HEIGHT;
                        addToGridBag(titleText, row, column, height);
                        unitPriceText = new JTextField("Unit Price");
                        unitPriceText.addActionListener(handler);
                        unitPrice.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(unitPriceText, row, column, height);
                        unitStockText = new JTextField("Units In Stock");
                        unitStockText.addActionListener(handler);
                        unitStockText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(unitStockText, row, column, height);
                        productValueText =new TextField("Product Value");
                        productValueText.addActionListener(handler);
                        productValueText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(productValueText, row, cloumn, height);
                             reStkfeeText =new JTextField("Restock Fee");
                        reStkfeeText.addActionListener(handler);
                        reStkfeeText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(reStkfeeText, row, cloumn, height);
                        //Creat vertical space.
                        row += TEXT_HEIGHT;
                        addToGridBag(new JLabel(""),row, column, height);
                        inventoryValueText =new TextField("Inventory Value");
                        inventoryValueText.addActionListener(handler);
                        inventoryValueText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(inventoryValueText, row, cloumn, height);
                        }//End the methods for building the TextFields.
                             //Add the main buttons to the frame.
                   private void buildMainButtons()
                             {//Declaraing the variables.
                             int row = 0;
                             int column = 0;
                             int width = 0;
                             int height = 0;                         
                             row =BUTTON_START_ROW;
                             column = BUTTON_COLUMN;
                             width = BUTTON_WIDTH;
                             height = BUTTON_HEIGHT;
                             constraints.weightx = 1;
                             constraints.weighty = 0;                         
                             //The constraints.fill = GridBagConstraints.HORIZONTAL;
                             ButtonHandler handler = new ButtonHandler();
                             //Creat a veritical space.
                             addToGridbag(new JLabel(""), row, column, width, height);
                             firstButton = new JButton("First");
                             firstButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(firstButton, row, column, width, height);                         
                             previousButton = new JButton("Previous");
                             previousButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(previousButton, row, column, width, height);     
                             nextButton = new JButton("Next");
                             nextButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(nextButton, row, column, width, height);     
                             lastButton = new JButton("Last");
                             lastButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(lastButton, row, column, width, height);     
                             addButton = new JButton("Add");
                             addButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(addButton, row, column, width, height);                         
                             deleteButton = new JButton("Delete");
                             deleteButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(deleteButton, row, column, width, height);
                             saveButton = new JButton("Save");
                             saveButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(saveButton, row, column, width, height);     
                             searchButton = new JButton("Search");
                             searchButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(searchButton, row, column, width, height);                         
                        //End methods for building the main butt0ns.
         private void addToGridBag(Component component, int row, int column, int width, int height)
         {               //Set up the upper-left corner of the component gridx and gridy.
                             constraints.gridx = column;
                             constraints.gridy = row;
                             //Set the numbers of rows and columns the components occupies.
                             constraints.gridwidth = width;
                             constraints.gridheight = height;
                             //set the constraints
                             Layout.setConstraints(component, constraints);
                             //Add the component to the JFrame.
                             add(component);                    
                        }//End method for addGridBag.                     
              //End class JLabelTextFieldViewGui.
    class Invetnory4
              public static void main(String args[])
                        {   //An array variable.
                             Product[]inventory;
                             inventory = new Product[10];
                             //Create and pass control to the GUI
                             FinalInventory gui = new FinaInventoryGUI(inventory);           
                        }//End method main
                   }//End class Inventory4     
    /*Inventory.java*/
    /*Means for importing program packages*/
    /*Beginning of the class type Inventory*/

    Hi Bryan,
    I took your advice and decided to take a different approach to the problem I am having, I decided to stay somewhat with the basics with little knowledge I have about coding. I am new to this and I am trying to learn through the fire but it's getting hot so if you don't mind, can you tell me what I need to do to fix the error messages I am getting.
    1. "else" without "if',
    2. can't load my icon-a JPG
    3. exception in thread amin
    process complete.
    4.Text area for displaying an iteration of the input
    the code is not as long as the other one! any help will be appreciated. Also I am attaching the code to the GUI that does work but I can not seem to get the actionListener aspect to work. Thanks again.
      //this one works and it serves as a model for what I am //trying to do in the fields. as well as designate a text area                                                              //where a each entry per iteration of input is displayed
    * @(#)InventoryGUIFrame.java
    * @author
    * @version 1.00 2008/2/2
    package components;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    * FormattedTextFieldDemo.java requires no other files.
    * It implements a mortgage calculator that uses four
    * JFormattedTextFields.
    public class InventoryGUIFrame extends JFrame
              String productName;
              String itemNumber;
              double unitPrice;
              double unitStock;
              //Labels to identify the fields
              private JLabel productNamelabel;
              private JLabel itemNumberlabel;
              private JLabel unitPricelabel;
              private JLabel unitStocklabel;
              //Fields for data Entry     
              private JTextField productNameField;
              private JTextField itemNumberField;
              private JTextField unitPriceField;
              private     JTextField unitStockField;
                   //Adding the JButtons
              JButton firstButton;
              JButton nextButton;
              JButton previousButton;
              JButton searchButton;
              JButton addButton;
              JButton deleteButton;
              JButton saveButton;
              //Constructor          
    public InventoryGUIFrame()
             super("Welcome To The Inventory Program");
             setLayout(new FlowLayout());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
             JFrame Frame = new JFrame();
             Frame JPanel = new Frame();
             JPanel  JLabel= new JPanel();
             TextArea area = new TextArea();
         productNamelabel = new JLabel("PRODUCT  NAME");
         productNamelabel.setToolTipText("Name of the item you wish to calculate");
        add(productNamelabel);
         productNameField= new JTextField(8);
         add(productNameField);
         itemNumberlabel = new JLabel("PRODUCT  NUMBER");
         itemNumberlabel.setToolTipText("Number identifying the product");
         add(itemNumberlabel);
         itemNumberField =new JTextField(5);
         add(itemNumberField);
         unitPricelabel=new JLabel("PRODUCT  PRICE");
         unitPricelabel.setToolTipText("What is the cost of the product?:");
         add(unitPricelabel);
         unitPriceField = new JTextField(5);
         add(unitPriceField);          
         unitStocklabel = new JLabel("UNITS  IN  STOCK");
         unitStocklabel.setToolTipText("How many products in inventory?:");
         add(unitStocklabel);
         unitStockField = new JTextField(5);
         add(unitStockField);
         firstButton =new JButton("First");
         add(firstButton);
         nextButton = new JButton("Next");
         add(nextButton);
         previousButton = new JButton("Previous");
         add(previousButton);
         addButton = new JButton("Add");
         add(addButton);
         deleteButton = new JButton("Delete");
         add(deleteButton);
         saveButton = new JButton("Save");
         add(saveButton);
         searchButton = new JButton("Search");
         add(searchButton);
         public static void main(String args[])
         InventoryGUIFrame frame  = new InventoryGUIFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(740,150);
         frame.setVisible(true);
      class InventorySystem6
    {     /*Declaration of products[] and the maximum storing capacity*/
       private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
       /*Prompts user to make another selection or exit program*/
       private static final String STOP_COMMAND = "stop";
            /*parameters defining maximun numbers of products available for storing in */
    private static final int MAX_NUM_OF_PRODUCTS = 100;
    /*Declaration of the variables */
    String name;
    String item;
    double stock;
    double price;
    double reStkfee=1.05;
    double pValue;
    double iValue;
    public InventorySystem6()
         /*Empty Constructor*/
    }/*Beginning of product input by the user*/
    public void inputProductInfo()
    {     /*Declaration of currency format*/     
                   DecimalFormat Currency = new DecimalFormat();
                   Scanner input = new Scanner(System.in);
                   /*Beginning of the Loop*/
                   JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
                   JOptionPane.PLAIN_MESSAGE);               
                   for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
                   name = JOptionPane.showInputDialog( "What is the Product Name? ");
                   if(name.equalsIgnoreCase("stop"))
                   break;
         String item = JOptionPane.showInputDialog("Enter the products ID");
         String priceStr =JOptionPane.showInputDialog("Enter the products price");
         double price=Double.parseDouble(priceStr);
                   String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
                   double stock = Double.parseDouble(stockStr);          
                   double sum=price*stock;
              JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
              JOptionPane.PLAIN_MESSAGE);
                   /* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
                   ,"\n","The Product Id is "+productId,"Product ID"
                        ,"\n","The Unit Price is"+unitPrice,"Unit Price"
                             ,"\n","The Units In Stock is"+unitStock,"UnitStock"
                                  ,"\n","The Product Value is"+productValue, "productValue"
                                       ,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
                                            ,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
                                                 ,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
                                                      ,"\n",JOptionPane.PLAIN_MESSAGE);*/
              //Product products[] = new Product[100];
                   products[i] = new Product();
                   products[i].setitem(item);
                   products[i].setname(name);
                   products[i].setprice(price);
                   products[i].setstock(stock);
                   products[i].setpValue(sum);
                   products[i].setreStkfee(reStkfee);
                   iValue += sum + products[i].getreStkfee();
    public void displayProductInfo()
    { /*Initialization of the variable total inventory value*/
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
              Product product = products[i];
              if(product==null)
              System.out.println(products[i]);
                   break;
         System.out.printf("product name: %s\n ", product.getname());
         System.out.printf("product ID: %s \n", product.getitem());
         System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getprice()));
         System.out.printf("units in Stock: %s \n", product.getstock());
         System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getpValue()));
         System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
         System.out.printf("Inventory Value: %s \n", iValue);
    }/*Beginning of method main*/
    public static void main(String[] args)
    {/*Message*/
         /*Means for retrieving and storing new data input into inventory program*/
    InventorySystem6 JTableImageCreator = new InventorySystem6();
    JTableImageCreator.displayProductInfo();
    JTableImageCreator.inputProductInfo();
    class Product
    /*Declaration of and default value of specified variables*/
    //private Product products[] = new Product[100];
    private String item;
    String name;
    private double stock;
    private double price;
    private double pValue;
    private double reStkfee;
    //private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
    private double iValue;
    /*method defining the get and set values of each individual variable*/
    public String getname()
    {/*Mean for storing and retrieving input of name*/
    return name;
    }/*Means for setting the product name*/
    public void setname(String name)
    {/*null pointer argument exception defining metod for obtainng product name*/
    this.name = name;
    }/*Means for getting the units identifcation number inputted by the user*/
    public String getitem()
    {/*Means for returning the user input*/
    return item;
    }/*Means for setting the units identifcation */
    public void setitem(String item)
    {/*null pointer argument exception for setting the product identification number*/
    this.item = item;
    }/*Means for getting the units value input*/
    public double getstock()
    {/*Means for returning the variable of the units*/
    return stock;
    }/*Means for setting the units value*/
    public void setstock(double stock)
    this.stock = stock;
    public double getprice()
    {/*Means for returning the dollar value of the price of the unit(s)*/
    return price;
    }/*Means for setting and requesting user to input + dollar amt*/
    public void setprice(double price)
    this.price = price ;
    }/*Means for setting the value of the total product value*/
    public void setpValue(double pValue)
    this.pValue = pValue+(price*stock);
    }/*Means for getting the value of the product*/
    public double getpValue()
    {/*Means for returning the value*/
         return pValue;
    }/*Means for getting the TtlInventoryValue of products entered*/
    public void setiValue(double iValue)
    {/*Condition Statement*/
              this.iValue=iValue;
    public double getiValue()
              return iValue;
    public void setreStkfee(double reStkfee)
         this.reStkfee=stock*price*1.05;
    /*Means for setting restockin fee of the total products*/
    public double getreStkfee()
    {/*Means for calculating the restocking fee of each products units nStock*/
                   return reStkfee;
    }/*Method for string the elements in [i] for display*/
    public String toString()
         {/*Means for returning defined string of elements in [i]*/
              return "Product{" +
    "item="+ item +
    ", name="+ name +
    ", stock="+ stock +
    ", price="+price +
    ", pValue="+pValue +
    ", reStkfee="+ reStkfee +
    ", iValue="+iValue+     
    }/*End set and get method*/
    }/*End of class Product*/
    /*Delcaration of the class type sortproductNames*/                    
    class sortproductNames extends Product
    {/*Declaration of the variable productName*/
    protected String name;
    /*Means for setting and getting values of the variable productName*/
    public void setname(String name)
    this.name = name;
    public String getname()
    return name;
    public int compareTo(Object object)
    { // for sorting by product name
    Product anotherProduct = (Product) object;
    return name.compareTo( anotherProduct.name);
                   g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
              else;
                   g.drawString("O2K", 10,10);
    * @(#)InventoryGUIFrame.java
    * @author
    * @version 1.00 2008/2/2
    package components;
    import java.io.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.imagio.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    * FormattedTextFieldDemo.java requires no other files.
    * It implements a mortgage calculator that uses four
    * JFormattedTextFields.
    public class InventoryGUIPanelFrameTextArea extends JFrame
    String productName;
    String itemNumber;
    double unitPrice;
    double unitStock;
    //Labels to identify the fields
    private JLabel productNamelabel;
    private JLabel itemNumberlabel;
    private JLabel unitPricelabel;
    private JLabel unitStocklabel;
    //Fields for data Entry     
    private JTextField productNameField;
    private JTextField itemNumberField;
    private JTextField unitPriceField;
    private     JTextField unitStockField;
    private Product[] products;
    private int unitStock;
    private int currentIndex=0;
    //Adding the JButtons
    JButton firstButton;
    JButton nextButton;
    JButton previousButton;
    JButton searchButton;
    JButton addButton;
    JButton deleteButton;
    JButton saveButton;
    //Constructor          
    public InventoryGUIPanelFrameTextArea()
    super("Welcome To The Inventory Program");
    this.products = products;
    this.numOfProducts = products;
    JFrame JPanel = new JFrame();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new GridLayout());
    showLogo();
    showLabels();
    showInputFields();
    showButtons();
    public void showLogo()
    O2K myLogo = new O2K();
    this.add(myLogo);
    public void showLabels()
    JPanel panel = new JPanel();
    panel.add(new JLabel("PRODUCT NAME"));
    panel.add(new JLabel("ITEM NUMBER"));
    panel.add(new JLabel("UNIT PRICE"));
    panel.add(new JLabel("UNITS IN STOCK"));
    this.add(panel);
    public void showInputFields()
    itemNumber =new JTextField(5);
    itemNumber.setEditable(false);
    productName= new JTextField(10);
    productName.setEditable(false);
    unitPrice= new JTextField(5);
    unitPrice.setEditable(false);
    unitStock = new JTextField(10);
    unitStock.setEditable(false);
    panel.setEditable(false);
    panel.add(itemNumber);
    panel.add(productName);
    panel.add(unitPrice);
    panel.add(unitStock);
    this.add(panel);
    public void showButtons()
    JPanel panel = new JPanel();
    first = new JButton("First");
    next = new JButton("Next");
    previous = new JButton("Previous");
    add = new JButton ("Add");
    delete = new JButton ("Delete");
    search = new JButton ("Search");
    save = new JButton ("Save");
    panel.add(first);
    panel.add(next);
    panel.add(previous);
    panel.add(add);
    panel.add(delete);
    panel.add(search);
    panel.add(save);
    panel.add(this);
    ButtonActionHandler handler = new ButtonActionHandler();
    first.addActionListener(handler);
    next.addActionListener(handler);
    previous.addActionListener(handler);
    add.addActionListener(handler);
    delete.addActionListener(handler);
    search.addActionListener(handler);
    save.addActinListener(handler);
    this.add(panel);
    setFields(0);
    protected void paintComponent (Graphics g)
    public void setFields(int i)
    setItemNumber(i);
    setProductName(i);
    setUnitPrice(i);
    setUnitStock(i);
    public void setItemNumber( int i)
    itemNumber.setText(products[i].getItemNumber());
    public void setProductName(int i)
    productname.setText(products[i].getProductName());
    public void setUnitPrice( int i)
    unitPrice.setText(String.valueOf(products[i].getunitPrice()));
    public void setUnitStock(int i)
    unitStock.setText(String.valueOf(products[i].getunitStock()));
    private class ButtonActionHandler implements ActionListener
    public void actionPerformed(ActionEvent event)
    if(event.getSource()==first)
    currentIndex=0;
    setFields(currentIndex);
    else if(event.getSource()==next)
    currentIndex++;
    if(currentIndex==unitStock);
    currentIndex--;
    setFields(currentIndex);
    else if (event.getSource()==previous)
    currentIndex--;
    if(curentIndex < 0)
    currentIndex=0;
    setFields(currentIndex);
    else if(event.getSource()==last)
    currentIndex = unitStock -1;
    setFields(currentIndex);
    else if(event.getSource()==add)
    currentIndex = productName ++;
    setFields(currentIndex);
    else if(event.getSource()==delete)
    currentIndex= productName -1;
    setFields(currentIndex);
    else if (event.getSource()==search)
    currentIndex=productName ++;
    setFields(currentIndex);
    else if (event.getSource()==save)
    currentIndex=productName ++;
    setFields(currentIndex);
    public static void main(String args[])
    JFrame mainFrame = new JFrame();
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(400,300);
    mainFrame.setVisible(true);
    class InventorySystem6
    {     /*Declaration of products[] and the maximum storing capacity*/
    private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
    /*Prompts user to make another selection or exit program*/
    private static final String STOP_COMMAND = "stop";
         /*parameters defining maximun numbers of products available for storing in [i]*/
    private static final int MAX_NUM_OF_PRODUCTS = 100;
    /*Declaration of the variables */
    String name;
    String item;
    double stock;
    double price;
    double reStkfee=1.05;
    double pValue;
    double iValue;
    public InventorySystem6()
         /*Empty Constructor*/
    }/*Beginning of product input by the user*/
    public void inputProductInfo()
    {     /*Declaration of currency format*/     
                   DecimalFormat Currency = new DecimalFormat();
                   Scanner input = new Scanner(System.in);
                   /*Beginning of the Loop*/
                   JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
                   JOptionPane.PLAIN_MESSAGE);               
                   for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
                   name = JOptionPane.showInputDialog( "What is the Product Name? ");
                   if(name.equalsIgnoreCase("stop"))
                   break;
         String item = JOptionPane.showInputDialog("Enter the products ID");
         String priceStr =JOptionPane.showInputDialog("Enter the products price");
         double price=Double.parseDouble(priceStr);
                   String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
                   double stock = Double.parseDouble(stockStr);          
                   double sum=price*stock;
              JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
              JOptionPane.PLAIN_MESSAGE);
                   /* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
                   ,"\n","The Product Id is "+productId,"Product ID"
                        ,"\n","The Unit Price is"+unitPrice,"Unit Price"
                             ,"\n","The Units In Stock is"+unitStock,"UnitStock"
                                  ,"\n","The Product Value is"+productValue, "productValue"
                                       ,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
                                            ,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
                                                 ,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
                                                      ,"\n",JOptionPane.PLAIN_MESSAGE);*/
              //Product products[] = new Product[100];
                   products[i] = new Product();
                   products[i].setItemNumber(itemNumber);
                   products[i].setPrdocutName(productName);
                   products[i].setUnitPrice(unitPrice);
                   products[i].setUnitStock(unitStock);
                   products[i].setProductValue(sum);
                   products[i].setReStkfee(reStkfee);
                   inventoryValue += sum + products[i].getreStkfee();
    public void displayProductInfo()
    { /*Initialization of the variable total inventory value*/
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
              Product product = products[i];
              if(product==null)
              System.out.println(products[i]);
                   break;
         System.out.printf("product name: %s\n ", product.getproductName());
         System.out.printf("product ID: %s \n", product.getitemNumber());
         System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getunitPrice()));
         System.out.printf("units in Stock: %s \n", product.getunitStock());
         System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getproductValue()));
         System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
         System.out.printf("Inventory Value: %s \n", inventoryValue);
    }/*Beginning of method main*/
    public static void main(String[] args)
    {/*Message*/
         /*Means for retrieving and storing new data input into inventory program*/
    InventorySystem6 JTableImageCreator = new InventorySystem6();
    JTableImageCreator.displayProductInfo();
    JTableImageCreator.inputProductInfo();
    class Product
    /*Declaration of and default value of specified variables*/
    //private Product products[] = new Product[100];
    protected String itemNumber;
    protected String prodcutname;
    protected double unitStock;
    protected double unitPrice;
    protected double productValue;
    protected double reStkfee;
    protected double inventoryValue;
    //private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
    /*method defining the get and set values of each individual variable*/
    public String getproductName()
    {/*Mean for storing and retrieving input of name*/
    return productName;
    }/*Means for setting the product name*/
    public void setProductName(String productName)
    {/*null pointer argument exception defining metod for obtainng product name*/
    this.productName = ProductName;
    }/*Means for getting the units identifcation number inputted by the user*/
    public String getitemNumber()
    {/*Means for returning the user input*/
    return itemNumber;
    }/*Means for setting the units identifcation */
    public void setItemNumber(String itemNumber)
    {/*null pointer argument exception for setting the product identification number*/
    this.itemNumber = itemNumber;
    }/*Means for getting the units value input*/
    public double getunitStock()
    {/*Means for returning the variable of the units*/
    return unitStock;
    }/*Means for setting the units value*/
    public void setUnitStock(double unitStock)
    this.unitStock = unitStock;
    public double getunitPrice()
    {/*Means for returning the dollar value of the price of the unit(s)*/
    return unitPrice;
    }/*Means for setting and requesting user to input + dollar amt*/
    public void setUnitPrice(double unitPrice)
    this.unitPrice = unitPrice ;
    }/*Means for setting the value of the total product value*/
    public void setProductValue(double prodcutValue)
    this.prodcutValue = unitPrice*unitStock;
    }/*Means for getting the value of the product*/
    public double getproductValue()
    {/*Means for returning the value*/
         return productValue;
    }/*Means for getting the TtlInventoryValue of products entered*/
    public void setInvetnoryValue(double invetnoryValue)
    {/*Condition Statement*/
              this.inventoryValue=inventoryValue;
    public double getinvetotyValue()
              return productValue;
    public void setReStkfee(double reStkfee)
         this.reStkfee=stock*price*1.05;
    /*Means for setting restockin fee of the total products*/
    public double getreStkfee()
    {/*Means for calculating the restocking fee of each products units nStock*/
                   return reStkfee;
    }/*Method for string the elements in [i] for display*/
    public String toString()
         {/*Means for returning defined string of elements in [i]*/
              return "Product{" +
    "itemNumber="+ itemNumber +
    ", productName="+ productName +
    ", unitStock="+ unitStock +
    ", unitPrice="+unitPrice +
    ", productValue="+prodcutValue +
    ", reStkfee="+ reStkfee +
    ", inventoryValue="+inventoryValue+     
    }/*End set and get method*/
    }/*End of class Product*/
    /*Delcaration of the class type sortproductNames*/                    
    class sortproductNames extends Product
    {/*Declaration of the variable productName*/
    protected String name;
    /*Means for setting and getting values of the variable productName*/
    public void setProdcutName(String productName)
    this.productName = productName;
    public String getproductName()
    return productName;
    public int compareTo(Object object)
    { // for sorting by product name
    Product anotherProduct = (Product) object;
    return productName.compareTo( anotherProduct.productName);
         class myGraphics extends component          
              private BufferedImage image;
              private boolean imageFound = true;
              public myGraphics()
                   super();
                   try
                        image=ImageIO.read(new File("Logo.jpg"));
                   catch(IOException x)
                        x.printStackTrace();
                        imageFound = false;
              public void paint(Graphics g)
                   g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
              else;
                   g.drawString("O2K", 10,10);

  • 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

  • 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

  • GridBag or Flow Layout: Help Please!!!

    Requirement: Allow the user to input the amount of a mortgage and then select from a menu of mortgage loans: 7 years at 5.35%, 15 years at 5.5%, and 30 years at 5.75%. Use an array for the different loans. Display the mortgage payment amount. Then, list the loan balance and interest paid for each payment over the term of the loan. Allow the user to loopback and enter a new amount and make a new selection or quit.
    I have written the code so far that allows for the creation of the pane, texts, user entry, combobox, and buttons.
    My problem is that I cannot get it sorted out to look like a usable interface. I don't know if I should go with a GridBag Layout or a Flow Layout.
    I am using the GridBag Layout in this example, but obviously I am missing the correct procedure on how to do it.
    Can anyone give me a hand?
    My goal for the interface is to have the following fields set up in the pane to lay out like this:
    Mortgage ------ MortgageTF
    Loan ----- LoanCB
    Payment ----- PaymentTF
    Balance
    Compute----- Reset----- Exit
    Thank you for any assistance.
    Havok
    My written code is below:
    import javax.swing.*;
    import java.awt.*;
    public class MCalc002 extends JFrame
    public MCalc002()
    super("Mortgage Calculator");
    setSize(500, 800);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    Container pane = getContentPane();
    GridBagLayout gridBag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    pane.setLayout(gridBag);
    JLabel mortgage = new JLabel("Mortgage:");
    c.gridx = 0; c.gridy = 0;
    pane.add(mortgage);
    JLabel loan = new JLabel("Loan Menu:");
    c.gridx = 2; c.gridy = 2;
    pane.add(loan);
    JLabel payment = new JLabel("Monthly Payment:");
    c.gridx = 3; c.gridy = 3;
    pane.add(payment);
    JLabel balance = new JLabel("Loan Balance:");
    c.gridx = 4; c.gridy = 4;
    pane.add(balance);
    JTextField mortgageTF = new JTextField(10);
    c.gridx = 4; c.gridy = 4;
    pane.add(mortgageTF);
    JComboBox loanCB = new JComboBox();
    c.gridx = 5; c.gridy = 5;
    loanCB.addItem("Please Select");
    loanCB.addItem("7yrs @ 5.35%");
    loanCB.addItem("15yrs @ 5.5%");
    loanCB.addItem("30yrs @ 5.75%");
    pane.add(loanCB);
    JTextField paymentTF= new JTextField(10);
    c.gridx = 4; c.gridy = 4;
    pane.add(paymentTF);
    JButton compute = new JButton("Compute");
    c.gridx = 5; c.gridy = 5;
    pane.add(compute, c);
    JButton reset = new JButton("Reset");
    c.gridx = 6; c.gridy = 6;
    pane.add(reset, c);
    JButton exit = new JButton("Exit");
    c.gridx = 7; c.gridy = 7;
    pane.add(exit, c);
    setContentPane(pane);
    public static void main(String[] arguments)
    MCalc002 pb = new MCalc002();
    //EOF

    My problem is that I cannot get it sorted out to look
    like a usable interface. I don't know if I should go
    with a GridBag Layout or a Flow Layout.
    My goal for the interface is to have the following
    fields set up in the pane to lay out like this:
    Mortgage ------ MortgageTF
    Loan ----- LoanCB
    Payment ----- PaymentTF
    Balance
    Compute----- Reset----- Exit
    import javax.swing.*;
    import java.awt.*;
    public class MCalc002 extends JFrame {
        public MCalc002() {
            super("Mortgage Calculator");
            setSize(500, 800);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container pane = getContentPane();
            GridBagLayout gridBag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            pane.setLayout(gridBag);
            JLabel mortgage = new JLabel("Mortgage:");
            c.gridx = 0; c.gridy = 0;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(mortgage, c);
            pane.add(mortgage);
            JLabel loan = new JLabel("Loan Menu:");
            c.gridx = 0; c.gridy = 1;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(loan, c);
            pane.add(loan);
            JLabel payment = new JLabel("Monthly Payment:");
            c.gridx = 0; c.gridy = 2;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(payment, c);
            pane.add(payment);
            JLabel balance = new JLabel("Loan Balance:");
            c.gridx = 0; c.gridy = 3;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(balance, c);
            pane.add(balance);
            JTextField mortgageTF = new JTextField(10);
            c.gridx = 3; c.gridy = 0;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(mortgageTF, c);
            pane.add(mortgageTF);
            JComboBox loanCB = new JComboBox();
            c.gridx = 3; c.gridy = 1;
            c.insets = new Insets(20,10,20,10);
            loanCB.addItem("Please Select");
            loanCB.addItem("7yrs @ 5.35%");
            loanCB.addItem("15yrs @ 5.5%");
            loanCB.addItem("30yrs @ 5.75%");
            gridBag.setConstraints(loanCB, c);
            pane.add(loanCB);
            JTextField paymentTF= new JTextField(10);
            c.gridx = 3; c.gridy = 2;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(paymentTF, c);
            pane.add(paymentTF);
            JButton compute = new JButton("Compute");
            c.gridx = 0; c.gridy = 4;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(compute, c);
            pane.add(compute, c);
            JButton reset = new JButton("Reset");
            c.gridx = 1; c.gridy = 4;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(reset, c);
            pane.add(reset, c);
            JButton exit = new JButton("Exit");
            c.gridx = 3; c.gridy = 4;
            c.insets = new Insets(20,10,20,10);
            gridBag.setConstraints(exit, c);
            pane.add(exit, c);
            setContentPane(pane);
            setVisible(true);  // Generally speaking, this should be the last operation in setting up GUI components.
        public static void main(String[] arguments) {
            MCalc002 pb = new MCalc002();
    }

  • 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;
    }

  • Gridbag layout - set size

    can I set a pixel width size for the cell of a gridbag?

    Set the minimum width and height as well as preferred width and height and let the layout manager take care of the size.
    You can not set the absolute width and height because components under GridbagLayout do not have adjustable size. Their size is determinded by layout manager, and the only thing you can set is the layout constraints and minimum/maximum/preferred size.

  • JTextArea & Gridbag layout

    Hello everyone:
    I am currnetly using a JTextArea with the Gridbag layout. I want to limit the size of the JTextArea. Found an article when I did a "search" that says the size is actually controlled by the layout manager. Have tried setMaximunSize(), no luck. It appears the layout manager ignores this. The problem I am having is that I can set the size I want, however if the user types a lot of text in to the JTextArea, the control expands and over and "pushes" the controls below it down. How do I keep the layout manager from allowing this to happen?
    Thanks in advance, Bart

    Have set the rows and columns as you suggested in the original code,and get the size I want initalially. The problem is that the JTextArea will increase past the size set so it "bleeds" downward. I looked in the Java book I have, and it says that the scrollbars for a JTextArea are provided automatically, however they do not appear when the user supplies more lines of text than there are rows. Instead the height of the control is enlarged and this in turn pushes the other controls on the pane down. Is this a mi-print in the book, ie the scroll bars are not automatically provide in a JTextArea?
    Thanks,
    Bart

Maybe you are looking for