aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Gridbag Layout Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Gridbag Layout" Watch "Gridbag Layout" New topic
Author

Gridbag Layout

rocket khera
Greenhorn

Joined: Sep 06, 2006
Posts: 1
Hi,

I am try to understand this layout manager.
But can not create a grid with 3 columns and any number of rows.
This first row is fine, but all rows after that do not show that first column.
Can anyone tell me why the first component in my rows do not appear ?

Thanks

Rocket


package guibase;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;

/**
*
* @author KheraR
*/
public class Main extends JPanel {

private static JMenuBar menuBar;
private JPanel mainPanel;
private JTextArea textArea;
private JSplitPane splitPane;
private int tableCounter, xCounter, yCounter = 0;

// Instantiate listeners
ActionListener myMenuActionListener = new MyMenuActionListener();

/** Creates a new instance of Main */
public Main() {

// Main panel
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
JScrollPane mainPanelView = new JScrollPane(mainPanel);
mainPanelView.setPreferredSize(new Dimension(660,240));

// Log panel
textArea = new JTextArea(5,30);
textArea.setLineWrap(true);
JScrollPane textAreaView = new JScrollPane(textArea);

// Set up the menu bar.
JMenu fileMenu = createFileMenu();
JMenu editMenu = createEditMenu();
menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(editMenu);

// Layout Display
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanelView, textAreaView);
splitPane.setOneTouchExpandable(true);
splitPane.setContinuousLayout(true);

add(splitPane, BorderLayout.CENTER);
}

/**
* Build File Menu
*/
public JMenu createFileMenu(){
JMenu menu = new JMenu("File");
JMenuItem menuItem = null;

// Open
menuItem = new JMenuItem("Add", KeyEvent.VK_A);
menuItem.getAccessibleContext().setAccessibleDescription("Add");
menuItem.addActionListener(myMenuActionListener);
menu.add(menuItem);
menu.addSeparator();

// Exit
menuItem = new JMenuItem("Exit");
menuItem.addActionListener(myMenuActionListener);
menu.add(menuItem);

return menu;
}

/**
* Build Edit Menu
*/
public JMenu createEditMenu(){
JMenu menu = new JMenu("Edit");
JMenuItem menuItem = null;

// Refresh
menuItem = new JMenuItem("Refresh");
menuItem.addActionListener(myMenuActionListener);
menu.add(menuItem);

return menu;
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBag Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
JComponent newContentPane = new Main();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.setJMenuBar(menuBar);

//Display the window.
frame.pack();
frame.setSize(700,400);
frame.setLocation(100,50);
frame.setVisible(true);
}

// The standard main method.
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();
}
});
}

public JTable getTable(){
System.out.println("\n** getTable()**");
JTable table = null;
table = new JTable(new MyTableModel());
table.setName("Table "+tableCounter);
JTableHeader header = table.getTableHeader();
header.setBackground(new Color(0).yellow);
header.setForeground(new Color(0).black);
header.setFont(new Font("Dialog",Font.BOLD,12));
table.setAutoResizeMode(table.AUTO_RESIZE_ALL_COLUMNS);
tableCounter++;
return table;
}

public void addTableToMainPanel(){
JTable table = getTable();
JScrollPane listScrollPane = new JScrollPane(table);
listScrollPane.setPreferredSize(new Dimension(100, 100));

GridBagConstraints gbc = new GridBagConstraints();

// Only allow 3 components accross - xCounter
if(xCounter>2){
textArea.append("** New Row \n");

gbc.weightx = 0.0;
gbc.weighty = 0.5;
gbc.gridwidth = 3;
gbc.gridx = 0;
gbc.gridy = yCounter++;
xCounter = 0;

}else{
gbc.weightx = 0.5;
gbc.weighty = 0.0;
gbc.gridx = xCounter;
gbc.gridy = yCounter;
}

textArea.append("X : "+xCounter+" Y : "+yCounter+" Table Counter : "+tableCounter+"\n");
xCounter++;

mainPanel.add(listScrollPane, gbc);

// This will repaint the splitPane
splitPane.resetToPreferredSizes();
}

// Table Model
class MyTableModel extends AbstractTableModel{
String[] columnNames = {"Table "+tableCounter};
Object [][] data = {{"Col 1"},{"Col 2"}};
public int getColumnCount(){
return columnNames.length;
}
public int getRowCount(){
return data.length;
}
public String getColumnName(int col){
return columnNames[col];
}
public Object getValueAt(int row, int col){
return data[row][col];
}
public Class getColumnClass(int c){
return getValueAt(0, c).getClass();
}
}


// Menu Listener
class MyMenuActionListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
JMenuItem menuItem = (JMenuItem)ae.getSource();

if(menuItem.getText().equals("Add")){
System.out.println("\n** MenuItem - Add**");
addTableToMainPanel();
}
if(menuItem.getText().equals("Refresh")){
mainPanel.removeAll();
textArea.setText(" ");
splitPane.resetToPreferredSizes();
xCounter = 0;
yCounter = 0;
tableCounter = 0;
}
if(menuItem.getText().equals("Exit")){
System.exit(0);
}
}
}

}
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

Welcome to JavaRanch!

I'm going to move this to our "Swing/AWT/SWT/JFace" forum, where this kind of question is more at home.


[Jess in Action][AskingGoodQuestions]
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
gbc.gridwidth = 3; means the next component should occupy
the space of all three columns.

Another way to do this:
Biliang Zhou
Ranch Hand

Joined: Jun 28, 2006
Posts: 43
Stay away from GridBag Layout...

It's not worth learning it, and even if you understand it during one project, you are going to forget the lousy details when you start another...

Anything that can be done by GridBag can be implemented by JGoodies FormLayout, with much less effort and greater elegance.

Just try google "JGoodies FormLayout" and you are on the right track!
Jared Cope
Ranch Hand

Joined: Aug 18, 2004
Posts: 243
Hi,

Originally posted by Biliang Zhou:

It's not worth learning it, and even if you understand it during one project, you are going to forget the lousy details when you start another...


I would not agree with this at all. I can't live without this layout (and yes I have tried jgoodies). It is just so powerful. The learning curve is steep, but very worth it in my opinion.

And what happens if you get put on a project that does use it? I guess you could refactor it all to use jgoodies but that would require understanding the gridbag layout code in the first place in order to translate it properly ...

Cheers, Jared.


SCJP 1.4 91%, SCJP 1.5 88%, SCJD B&S
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I agree that understanding how GridbagLayout works is good if you are forced to. Using it voluntarily? Well, not me. But to each his own, I guess...

http://madbean.com/anim/totallygridbag


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Biliang Zhou
Ranch Hand

Joined: Jun 28, 2006
Posts: 43
I would not agree with this at all. I can't live without this layout (and yes I have tried jgoodies). It is just so powerful. The learning curve is steep, but very worth it in my opinion.


Sure, GridBag is powerful, but it comes with the price tag of a sharp learning curve. It can do some really tricky tasks, which can be mission impossible for other layouts. But how often do beginners and mid-level swing programmers use GridBag layout in a complex way? I see the initiator of this thread as one who is learning the layout managers. So I suggest spend less time on GridBag.


And what happens if you get put on a project that does use it? I guess you could refactor it all to use jgoodies but that would require understanding the gridbag layout code in the first place in order to translate it properly ...


That is not exactly true... If you need to refactor a GUI you can just run the application, do a screen capture, and start from the screen capture to "interpret" it. How long does it take to interpret a GridBag Layout into a JGoodies FormLayout? No more than 10 minutes if you have a screen capture to look at!
Jared Cope
Ranch Hand

Joined: Aug 18, 2004
Posts: 243
Hi,

Originally posted by Biliang Zhou:

If you need to refactor a GUI you can just run the application, do a screen capture, and start from the screen capture to "interpret" it.


But what happens when you resize the screen in different ways? Components move around and get different sizes. How many screen captures do you need then to see all the required behaviour? If you know how to read gridbag layout contraints you will just know what will happen in all situations.

But at the end of the day, they are all just tools to get the job done.

Cheers, Jared.
Biliang Zhou
Ranch Hand

Joined: Jun 28, 2006
Posts: 43
But at the end of the day, they are all just tools to get the job done.


That's true, that's true. Can't agree more. Hope someday these tools can be more intelligent to make life a little bit easier for us...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Gridbag Layout