GridBagLayout - different row size - java

normally, i'm not that bad with Swing and the different Layouts, but this one is really bugging me out.
What's wrong on the following chart using GridBagLayout? Every thick rectange is an JPanel.
The thin lines are just helper for the right y values.
Thanks in advance!
package at;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridMask extends JFrame {
JPanel jPanel1, jPanel2, jPanel3, jPanel4, jPanel5, jPanel6;
public GridMask() {
unimportantStuff();
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
GridBagConstraints gbc;
gbc = getGbc(0, 0, 3, 1, 0.5);
gbl.setConstraints(jPanel1, gbc);
gbc = getGbc(1, 0, 4, 1, 0.75);
gbl.setConstraints(jPanel2, gbc);
gbc = getGbc(2, 0, 3, 1, 0.5);
gbl.setConstraints(jPanel3, gbc);
gbc = getGbc(0, 3, 3, 1, 0.5);
gbl.setConstraints(jPanel4, gbc);
gbc = getGbc(1, 4, 2, 1, 0.25);
gbl.setConstraints(jPanel5, gbc);
gbc = getGbc(2, 3, 3, 1, 0.5);
gbl.setConstraints(jPanel6, gbc);
add(jPanel1);
add(jPanel2);
add(jPanel3);
add(jPanel4);
add(jPanel5);
add(jPanel6);
setVisible(true);
}
private GridBagConstraints getGbc(int x, int y, int height, int width, double weightY) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = height;
gbc.gridwidth = width;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = weightY;
return gbc;
}
private void unimportantStuff() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jPanel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel5.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jPanel6.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public static void main(String[] args) {
new GridMask();
}
}
The result is a JFrame where the two rows have different heights, but the cells in a row have all the same height.

but the cells in a row have all the same height.
gbc.fill = GridBagConstraints.BOTH;
You are telling the layout to size all the components to fill the space available in each cell.

Related

putting a JPanel in a JFrame: setContentPane() and add() both work?

putting a JPanel in a JFrame: setContentPane() and add() both seem to work. Is there any technical difference?
One example from web has the following. Changing frame.setContentPane(panel) to frame.add(panel) seems to produce the same behavior.
//file: Calculator.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
GridBagConstraints gbc = new GridBagConstraints();
JTextField theDisplay = new JTextField();
public Calculator() {
gbc.weightx = 1.0; gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
ContainerListener listener = new ContainerAdapter() {
public void componentAdded(ContainerEvent e) {
Component comp = e.getChild();
if (comp instanceof JButton)
((JButton)comp).addActionListener(Calculator.this);
}
};
addContainerListener(listener);
gbc.gridwidth = 4;
addGB(this, theDisplay, 0, 0);
// make the top row
JPanel topRow = new JPanel();
topRow.addContainerListener(listener);
gbc.gridwidth = 1;
gbc.weightx = 1.0;
addGB(topRow, new JButton("C"), 0, 0);
gbc.weightx = 0.33;
addGB(topRow, new JButton("%"), 1, 0);
gbc.weightx = 1.0;
addGB(topRow, new JButton("+"), 2, 0 );
gbc.gridwidth = 4;
addGB(this, topRow, 0, 1);
gbc.weightx = 1.0; gbc.gridwidth = 1;
// make the digits
for(int j=0; j<3; j++)
for(int i=0; i<3; i++)
addGB(this, new JButton("" + ((2-j)*3+i+1) ), i, j+2);
// -, x, and divide
addGB(this, new JButton("-"), 3, 2);
addGB(this, new JButton("x"), 3, 3);
addGB(this, new JButton("\u00F7"), 3, 4);
// make the bottom row
JPanel bottomRow = new JPanel();
bottomRow.addContainerListener(listener);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("0"), 0, 0);
gbc.weightx = 0.33;
addGB(bottomRow, new JButton("."), 1, 0);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("="), 2, 0);
gbc.gridwidth = 4;
addGB(this, bottomRow, 0, 5);
}
void addGB(Container cont, Component comp, int x, int y) {
if ((cont.getLayout() instanceof GridBagLayout) == false)
cont.setLayout(new GridBagLayout());
gbc.gridx = x; gbc.gridy = y;
cont.add(comp, gbc);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("C"))
theDisplay.setText("");
else
theDisplay.setText(theDisplay.getText()
+ e.getActionCommand());
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 250);
frame.setLocation(200, 200);
frame.setContentPane(new Calculator());
frame.setVisible(true);
}
}
Another has the following. Changing frame.add(panel) to frame.setContentPane(panel) seems to produce the same behavior.
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class recMod {
public enum RecFieldNames {
FIRST_NAME("First Name:"),
LAST_NAME("Last Name:"),
VENDOR("Vendor:"),
VENDOR_LOC_CODE("Vendor Location Code:"),
USER_EMAIL("User Email Address:"),
USER_NAME("Username:"),
PASSWORD("Password:"),
USER_CODE("User Code:");
private String name;
private RecFieldNames(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static final int FIELD_COLS = 7;
private Map<RecFieldNames, JTextField> recFieldMap =
new HashMap<RecFieldNames, JTextField>();
//JButton[] recButtons = new JButton[3];
public recMod() {
JFrame frame = new JFrame("Record Modify");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
addLabelField(panel, RecFieldNames.FIRST_NAME, 0, 0, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.LAST_NAME, 2, 0, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.EAST);
addLabelField(panel, RecFieldNames.VENDOR, 0, 1, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.VENDOR_LOC_CODE, 2, 1, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_EMAIL, 0, 2, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_NAME, 0, 3, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.PASSWORD, 2, 3, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_CODE, 0, 4, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
//frame.getContentPane().setPreferredSize(new Dimension(500, 400));
((JComponent) frame.getContentPane()).
setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public String getFieldText(RecFieldNames rfn) {
return recFieldMap.get(rfn).getText();
}
private void addLabelField(JPanel p, RecFieldNames recFieldNames, int x,
int y, int width, int height, int labelAlign, int fieldAlign) {
GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel(recFieldNames.getName());
JTextField textField = new JTextField(FIELD_COLS);
recFieldMap.put(recFieldNames, textField);
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
int midInset = (x == 2) ? 40 : 5;
gbc.insets = new Insets(5, midInset, 5, 5);
gbc.anchor = labelAlign;
gbc.fill = GridBagConstraints.HORIZONTAL;
p.add(label, gbc);
gbc.gridx = x + 1;
gbc.anchor = fieldAlign;
gbc.insets = new Insets(5, 5, 5, 5);
p.add(textField, gbc);
}
public static void main(String args[]) {
new recMod();
}
}
The content pane of the frame is a JPanel.
So if you use frame.add( another panel ), then you have a structure like:
- JFrame
- content pane
- another panel
If you use frame setContentPane( another panel ) you have:
- JFrame
- another panel
See the section from the Swing tutorial on Adding Components to the Content Pane.

Componenets alignment in GridBagLayout

I am using GridBagLayout to align components. Actually, i have two buttons which i want to align like this:
Desired layout:
But the following code results in the following layout:
Resulted layout:
My code:
iconAdd = new ImageIcon(getClass().getResource("../images/add.png"));
add = new JButton(iconAdd);
add.setPreferredSize(new Dimension(130, 100));
add.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
add.setCursor(Cursor.getPredefinedCursor(12));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
pane.add(add, gbc);
iconSearch = new
ImageIcon(getClass().getResource("../images/search.png"));
search = new JButton(iconSearch);
search.setCursor(Cursor.getPredefinedCursor(12));
search.setPreferredSize(new Dimension(130, 100));
search.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
pane.add(search, gbc);
Any help would be highly appreciated.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayoutDemo extends JFrame{
GridBagLayoutDemo(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWeights = new double[]{1.0, 1.0, 1.0};
gridBagLayout.columnWidths = new int[]{0,0,300};
getContentPane().setLayout(gridBagLayout);
JButton button1 = new JButton("Long Button");
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.HORIZONTAL;
c1.weightx = 0.0;
c1.gridwidth = 3;
c1.gridx = 0;
c1.gridy = 0;
getContentPane().add(button1, c1);
JButton button2 = new JButton("Button 2");
GridBagConstraints c2 = new GridBagConstraints();
c2.weightx = 0.5;
c2.gridx = 0;
c2.gridy = 1;
getContentPane().add(button2, c2);
JButton button3 = new JButton("Button 3");
GridBagConstraints c3 = new GridBagConstraints();
c3.weightx = 0.5;
c3.gridx = 1;
c3.gridy = 1;
getContentPane().add(button3, c3);
pack();
setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GridBagLayoutDemo();
}
});
}
}
gbc.weightx = 1;
You are telling the layout to give extra space to each component. So essentially each component becomes half the size of the frame.
You really only want that constraint set for the second button, so it takes up all the remaining space.
Read the section from the Swing tutorial on How to Use GridBagLayout which explains how the weightx/y constraints should be used.
Also, an easier solution would be do just use a FlowLayout. Create a panel with a FlowLayout. Add the buttons to the panel. Then add the panel to the BorderLayout.PAGE_START of the frame.

How to place GUI object at specific x/y place within cell within GridBagLayout

I'm new to Java Swing and am doing a small project to help me get familiar to use it. I'm trying to specify the placement dimensions of my objects (and their sizes), but I can't seem to get it right. I have the Object sizes presenting correct, but can't place them where I want. Below is an example of what it currently looks like, and what I'm looking for...
Currently...
Need to make it look like...
Below is the code I drummed up...
package Main;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import org.apache.commons.lang3.ArrayUtils;
public class StartGui extends JFrame implements ActionListener {
private static final String[] GuiCharSelDefault = {"--- Select Character ---"};
private static final int unselectedDefaultElement = 0;
private static final String[] GuiCharSel = (String[])ArrayUtils.addAll(GuiCharSelDefault, Calculator.Characters);
private String[] lvlRange = SupportMethods.createArrRange("- -", 1, 99);
/*
* Interactive GUI Objects
*/
JLabel charPic;
JComboBox charSelCombo = new JComboBox(GuiCharSel);
JComboBox pickLvlAns = new JComboBox(lvlRange);
JLabel nextLvlAns = new JLabel("- -");
public StartGui() {
/*
* Non-Interactive GUI Objects
*/
JPanel topFrame = new JPanel();
JPanel bottomFrame = new JPanel();
JPanel selPane = new JPanel();
JLabel pickLvl = new JLabel("Pick Current Level:");
JLabel nextLvl = new JLabel("Next Level:");
//*******************************************************************************
/*
* Top Frame Settings
*/
TitledBorder topFrameTitle;
Border blackLine = BorderFactory.createLineBorder(Color.black);
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder(raisedBevel, loweredBevel);
topFrameTitle = BorderFactory.createTitledBorder(compound, "Character");
topFrameTitle.setTitleJustification(TitledBorder.CENTER);
topFrame.setBorder(topFrameTitle);
topFrame.setLayout(new BoxLayout(topFrame, BoxLayout.X_AXIS));
/*
* Adds Character Picture
*/
charPic = new JLabel("", null, JLabel.CENTER);
charPic.setPreferredSize(new Dimension(100,100));
topFrame.add(charPic);
//*******************************************************************************
/*
* Selection Pane Settings
*/
selPane.setLayout(new GridBagLayout());
selPane.setBorder(blackLine);
/*
* Adds Character Selection ComboBox
*/
charSelCombo.setPrototypeDisplayValue(charSelCombo.getItemAt(unselectedDefaultElement));
selPane.add(charSelCombo, setGbc(0,0, "WEST", 0, 1, setInsets(0, 10, 0, 0)));
/*
* Adds "Pick Current Level:" Label
*/
selPane.add(pickLvl, setGbc(0,1, "EAST", 0, 1, setInsets(0, 0, 0, 0)));
/*
* Adds "Next Level:" Label
*/
selPane.add(nextLvl, setGbc(0,2, "EAST", 0, 1, setInsets(0, 0, 0, 0)));
/*
* Adds Character Current Level ComboBox
*/
pickLvlAns.setPrototypeDisplayValue(pickLvlAns.getItemAt(lvlRange.length - 1));
selPane.add(pickLvlAns, setGbc(1,1, "WEST", 1, 1, setInsets(0, 10, 0, 0)));
/*
* Adds Character Next Level Label
*/
selPane.add(nextLvlAns, setGbc(1,2, "WEST", 1, 1, setInsets(0, 23, 0, 0)));
//*******************************************************************************
/*
* BOTTOM PANE
*/
TitledBorder bottomFrameTitle;
bottomFrameTitle = BorderFactory.createTitledBorder(compound, "Stats");
bottomFrameTitle.setTitleJustification(TitledBorder.CENTER);
bottomFrame.setBorder(bottomFrameTitle);
//*******************************************************************************
/*
* Display everything in GUI to user
*/
add(topFrame, BorderLayout.NORTH);
add(bottomFrame,BorderLayout.CENTER);
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent arg0) {
String charName = ((JComboBox)(arg0.getSource())).getSelectedItem().toString();
String image = "../images/"+charName+".png";
charPic.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource(image)).getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH)));
charSelCombo.removeItem(GuiCharSel[unselectedDefaultElement]);
pickLvlAns.removeItem(lvlRange[unselectedDefaultElement]);
}
private GridBagConstraints setGbc(int gridx, int gridy, String anchorLocation, double weightx, double weighty, Insets insets){
GridBagConstraints gbc = new GridBagConstraints();
if (anchorLocation.toUpperCase().equals("NORTHWEST")){
gbc.anchor = GridBagConstraints.NORTHWEST;
} else if (anchorLocation.toUpperCase().equals("NORTH")){
gbc.anchor = GridBagConstraints.NORTH;
} else if (anchorLocation.toUpperCase().equals("NORTHEAST")){
gbc.anchor = GridBagConstraints.NORTHEAST;
} else if (anchorLocation.toUpperCase().equals("WEST")){
gbc.anchor = GridBagConstraints.WEST;
} else if (anchorLocation.toUpperCase().equals("EAST")){
gbc.anchor = GridBagConstraints.EAST;
} else if (anchorLocation.toUpperCase().equals("SOUTHWEST")){
gbc.anchor = GridBagConstraints.SOUTHWEST;
} else if (anchorLocation.toUpperCase().equals("SOUTH")){
gbc.anchor = GridBagConstraints.SOUTH;
} else if (anchorLocation.toUpperCase().equals("SOUTHEAST")){
gbc.anchor = GridBagConstraints.SOUTHEAST;
} else {
gbc.anchor = GridBagConstraints.CENTER;
}
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.insets = insets;
return gbc;
}
private Insets setInsets(int top, int left, int bottom, int right){
Insets insets = new Insets(top,left,bottom,right);
return insets;
}
public static void main(String[] args) {
new StartGui();
}
}
If anyone could tell me if there is a way to do this, it would really help a alot
Edit: With the help from MadProgrammer, I did some tweaking to the code above which actually made it work.
weightx and weighty determine how much of the left over space is supplied to the given column/row. If you supply a weightx/y value to two or more columns/rows, the space is divided between them, so, setting the weightx of column 1 and 2, like you have, means that they share 50% of the left of space, which is why it's looking the way it is.
Instead, only the last column really needs to have a weightx value at all
selPane.setLayout(new GridBagLayout());
selPane.setBorder(blackLine);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(2, 2, 2, 2);
charSelCombo.setPrototypeDisplayValue("Hello");
selPane.add(charSelCombo, gbc);
gbc.gridy++;
selPane.add(pickLvl, gbc);
gbc.gridy++;
selPane.add(nextLvl, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
selPane.add(pickLvlAns, gbc);
gbc.gridy++;
selPane.add(nextLvlAns, gbc);
I simplified the code a little (for me). One of the nice things about GridBagConstraints is, GridBagLayout will make a copy of the constraints you supply, so you can share it among multiple components, like I have above, it makes it easier to update and modify, as you maintain the overall relationship between the components

Check if a slot of a GridBayLayout is empty

Suppose you have a panel initialized like so
JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setBounds(249, 165, 71, 227);
panel_playerBuffs.setOpaque(false);
panel_playerBuffs.setLayout(new GridBagLayout());
getContentPane().add(panel_playerBuffs);
And its layout is GridBayLayout with the following constraints
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
panel_playerBuffs.add(new JLabel("located at 1, 3"), gbc);
As you can see, this adds a JLabel at (1, 1) and another one at (1, 3). Now I'm trying to add a conditional somewhere else in the program to check whether or not there's a label at a given position. For instance, I would like to find out if the position (1, 2) has a label (in this case it doesn't). What method should I use for this?
How about using the GridBagLayout#getLayoutDimensions()
If the width or height of the given position is 0, there is empty.
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
public class GridBayLayoutSlotTest {
private JComponent makeUI() {
GridBagLayout layout = new GridBagLayout();
JPanel panel_playerBuffs = new JPanel();
panel_playerBuffs.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 1;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 1, 1"), gbc);
gbc.gridx = 3;
gbc.gridy = 1;
panel_playerBuffs.add(new JLabel("located at 3, 1"), gbc);
EventQueue.invokeLater(() -> {
int[][] a = layout.getLayoutDimensions();
System.out.println(Arrays.deepToString(a));
System.out.format("isEmpty(%d, %d): %s%n", 2, 1, isEmpty(a, 2, 1));
System.out.format("isEmpty(%d, %d): %s%n", 3, 1, isEmpty(a, 3, 1));
});
return panel_playerBuffs;
}
private static boolean isEmpty(int[][] a, int x, int y) {
int[] w = a[0];
int[] h = a[1];
return w[x] == 0 || h[y] == 0;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new GridBayLayoutSlotTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

Unable to add make JTextArea show multiplie lines insidea JScrollPane

I am trying to make multiple lines of a JTextArea visible.I am using GridBagLayout to add the components. Here is a code snippet:
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class SSCE {
SSCE(){
JFrame f1=new JFrame();
GridBagLayout gbl=new GridBagLayout();
JButton btnAddAcc=new JButton("Add Acount");
JButton insertId=new JButton("Insert");
JButton insertTweet=new JButton("Insert2");
JButton tweetButton=new JButton("TweetButton");
JLabel accountStatusHeader=new JLabel("account status Header");
JLabel accountDisplayNameHeader=new JLabel("account displayname Header");
JLabel enterInterval=new JLabel("enter Interval!!");
final JTextArea accountDispName = new JTextArea(50, 50);
final JTextArea statusDisplay = new JTextArea(50, 50);
final JTextArea jTextAreaId = new JTextArea(20, 50);
final JTextArea jTextAreaTweets = new JTextArea(20, 50);
jTextAreaId.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.PINK, Color.GREEN));
final JTextArea tweetLog = new JTextArea(100, 100);
tweetLog.setPreferredSize(new Dimension(1000, 5000));
JScrollPane tweetLogPaneScroll = new JScrollPane(tweetLog);
JScrollPane idScrollPane = new JScrollPane(jTextAreaId);
JScrollPane tweetScrollPane = new JScrollPane(jTextAreaTweets);
final JTextField timeIntervalInput = new JTextField(20);
final JTextField tagIdInsertTextBox = new JTextField(50);
final JTextField tweetInsertTextBox = new JTextField(50);
f1.setLayout(gbl);
f1.add(btnAddAcc,makeGbc(0,0,1,2));
f1.add(accountDisplayNameHeader,makeGbc(1,0));
f1.add(accountStatusHeader,makeGbc(1,1));
f1.add(accountDispName,makeGbc(2,0));
f1.add(statusDisplay,makeGbc(2,1));
f1.add(enterInterval,makeGbc(3,0));
f1.add(timeIntervalInput,makeGbc(3,1));
f1.add(new JLabel("Twitter Ids"),makeGbc(4,0));
f1.add(new JLabel("Tweets"),makeGbc(4,1));
f1.add(idScrollPane,makeGbc(5,0,5));
f1.add(tweetScrollPane,makeGbc(5,1,5));
f1.add(tagIdInsertTextBox,makeGbc(10,0));
f1.add(tweetInsertTextBox,makeGbc(10,1));
f1.add(insertId,makeGbc(11,0));
f1.add(insertTweet,makeGbc(11,1));
f1.add(tweetButton,makeGbc(12,0,1,2));
f1.add(tweetLogPaneScroll,makeGbc(13,0,6,2));
f1.setSize(800,400);
f1.setVisible(true);
f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
accountDispName.setVisible(false);
statusDisplay.setVisible(false);
}
private GridBagConstraints makeGbc(int y, int x) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
// gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x,int gridheight) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x,int gridheight,int gridwidth) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
public static void main(String args[]){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SSCE a1;
a1 = new SSCE();
}
});
}
}
Please note the following lines:
f1.add(idScrollPane,makeGbc(5,0,5));
f1.add(tweetScrollPane,makeGbc(5,1,5));
In above, I am passing the third paramenter(the gridheight) as 5 but still I see only one row. I want to set the row span to 5.
And Also the following:
f1.add(tweetLogPaneScroll,makeGbc(13,0,6,2));
Here again, I am passing the third param(gridheight) as 6.But yet I see only one Row of textarea. So what is going wrong?? And whats the solution?
Your SSCCE helps me to see everything -- thanks! I've voted to open your question and have up-voted it. You're killing yourself with your unrealistic JTextArea row numbers, and then setting the size of your GUI. Get rid of all setSize(...) and setPreferredSize(...) method calls. Make your JTextArea row counts 5 or 10, not 50, not 100. Call pack() before setVisible(true).
For example, please see the changes I've made below as well as comments with !! in them. Note that I've tried to get rid of most of your magic numbers, but you still need to do the same with the column counts. I've also added text to your text components for the sake of debugging, so that I can see at a glance which text component goes with which variable. You'll of course not want to have this text present in the presentation code, but again, it's a useful debugging tool:
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
public class SSCE {
private static final int SMALL_ROWS = 5; // !! was 20!
private static final int BIG_ROWS = 10; // !! was 50!
SSCE() {
JFrame f1 = new JFrame();
GridBagLayout gbl = new GridBagLayout();
JButton btnAddAcc = new JButton("Add Acount");
JButton insertId = new JButton("Insert");
JButton insertTweet = new JButton("Insert2");
JButton tweetButton = new JButton("TweetButton");
JLabel accountStatusHeader = new JLabel("account status Header");
JLabel accountDisplayNameHeader = new JLabel(
"account displayname Header");
JLabel enterInterval = new JLabel("enter Interval!!");
final JTextArea accountDispName = new JTextArea("accountDispName JTA",
BIG_ROWS, 50);
final JTextArea statusDisplay = new JTextArea("statusDisplay JTA",
BIG_ROWS, 50);
final JTextArea jTextAreaId = new JTextArea("jTextAreaId JTA",
SMALL_ROWS, 50);
final JTextArea jTextAreaTweets = new JTextArea("jTextAreaTweets JTA",
SMALL_ROWS, 50);
jTextAreaId.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
Color.PINK, Color.GREEN));
final JTextArea tweetLog = new JTextArea("tweetLog JTA", BIG_ROWS, 100); // was
// 100!
// !! tweetLog.setPreferredSize(new Dimension(1000, 5000));
JScrollPane tweetLogPaneScroll = new JScrollPane(tweetLog);
JScrollPane idScrollPane = new JScrollPane(jTextAreaId);
JScrollPane tweetScrollPane = new JScrollPane(jTextAreaTweets);
final JTextField timeIntervalInput = new JTextField(
"timeIntervalInput JTF", 20);
final JTextField tagIdInsertTextBox = new JTextField(
"tagIdInsertTextBox JTF", 50);
final JTextField tweetInsertTextBox = new JTextField(
"tweetInsertTextBox JTF", 50);
f1.setLayout(gbl);
f1.add(btnAddAcc, makeGbc(0, 0, 1, 2));
f1.add(accountDisplayNameHeader, makeGbc(1, 0));
f1.add(accountStatusHeader, makeGbc(1, 1));
f1.add(accountDispName, makeGbc(2, 0));
f1.add(statusDisplay, makeGbc(2, 1));
f1.add(enterInterval, makeGbc(3, 0));
f1.add(timeIntervalInput, makeGbc(3, 1));
f1.add(new JLabel("Twitter Ids"), makeGbc(4, 0));
f1.add(new JLabel("Tweets"), makeGbc(4, 1));
f1.add(idScrollPane, makeGbc(5, 0, 5));
f1.add(tweetScrollPane, makeGbc(5, 1, 5));
f1.add(tagIdInsertTextBox, makeGbc(10, 0));
f1.add(tweetInsertTextBox, makeGbc(10, 1));
f1.add(insertId, makeGbc(11, 0));
f1.add(insertTweet, makeGbc(11, 1));
f1.add(tweetButton, makeGbc(12, 0, 1, 2));
f1.add(tweetLogPaneScroll, makeGbc(13, 0, 6, 2));
// !! f1.setSize(800, 400);
f1.pack(); // !!
f1.setVisible(true);
f1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
accountDispName.setVisible(false);
statusDisplay.setVisible(false);
}
private GridBagConstraints makeGbc(int y, int x) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
// gbc.gridheight = 1;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
System.out.printf("gridwidth, gridheight: [%d, %d]%n", gbc.gridwidth,
gbc.gridheight);
return gbc;
}
private GridBagConstraints makeGbc(int y, int x, int gridheight) {
GridBagConstraints gbc = new GridBagConstraints();
// gbc.gridwidth = 1;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private GridBagConstraints makeGbc(int y, int x, int gridheight,
int gridwidth) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.gridx = x;
gbc.gridy = y;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = (y == 0) ? GridBagConstraints.LINE_START
: GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SSCE a1;
a1 = new SSCE();
}
});
}
}
This results in a GUI that looks like so:
Note, I would also change the GridBagConstraints for JTextFields from BOTH to HORIZONTAL.
Edit
You state in comment:
One more question if u dont mind answering.the TimeIntervalInput is appearing so wide although I have defined it to hold at max 20 chars.Any solution to that?
You need to continue to play with your grid bag constraints as the ones you're using are quite restrictive. For example, note what happens when I use more exacting constraints on the GBC for that JTextField:
GridBagConstraints gbc = makeGbc(3, 1);
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
f1.add(timeIntervalInput, gbc);

Categories