I'm trying to make a simple game involving a 10x10 grid, where each cell in the grid will need to contain a large letter in the center, and a small number in one of the corners. Like this:
Currently, the best idea I've had involves making 100 different JLabel components that correspond to each cell from jLabel00 to jLabel99, and using null layout to manually layer them over the bottom-right corner of each cell of a Table. However, this is going to cause a lot of repetitiveness in my code and UI even if I add the labels to an ArrayList (assuming I can even do that).
Does anyone know of a more elegant solution?
The kind of layout seen above can easily be made using a GridBagLayout for the 'cells' and a GridLayout to arrange those cells in rows. The code could use a factory method to produce the cells. It might take a number and a char or single character String for the letter. This code 'cheats' by assuming the number is a Unicode code point.
This is the method that makes a cell panel:
private JPanel getCellPanel(int i) {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(new LineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
JLabel l1 = new JLabel(new String(Character.toChars(i)));
l1.setFont(l1.getFont().deriveFont(30f));
gbc.gridx = 0;
gbc.gridy = 0;
p.add(l1, gbc);
JLabel l2 = new JLabel();
gbc.gridx = 0;
gbc.gridy = 1;
p.add(l2, gbc);
JLabel l3 = new JLabel();
gbc.gridx = 1;
gbc.gridy = 0;
p.add(l3, gbc);
JLabel l4 = new JLabel(new String("" + i));
l4.setFont(l4.getFont().deriveFont(12f));
gbc.gridx = 1;
gbc.gridy = 1;
p.add(l4, gbc);
return p;
}
The complete source code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BigLetterLittleNumber {
private JComponent ui = null;
BigLetterLittleNumber() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new GridLayout(0, 13, 2, 2));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
for (int ii=65; ii<91; ii++) {
ui.add(getCellPanel(ii));
}
}
private JPanel getCellPanel(int i) {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(new LineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
JLabel l1 = new JLabel(new String(Character.toChars(i)));
l1.setFont(l1.getFont().deriveFont(30f));
gbc.gridx = 0;
gbc.gridy = 0;
p.add(l1, gbc);
JLabel l2 = new JLabel();
gbc.gridx = 0;
gbc.gridy = 1;
p.add(l2, gbc);
JLabel l3 = new JLabel();
gbc.gridx = 1;
gbc.gridy = 0;
p.add(l3, gbc);
JLabel l4 = new JLabel(new String("" + i));
l4.setFont(l4.getFont().deriveFont(12f));
gbc.gridx = 1;
gbc.gridy = 1;
p.add(l4, gbc);
return p;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BigLetterLittleNumber o = new BigLetterLittleNumber();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
I'm trying to create a personal DnD character sheet program. The main idea is to have 4 large panels that each contain one of the major sections of a basic character sheet. I'm currently working on the first panel that has stats and saving throws. I'm trying to get more comfortable with GridBagLayout while making this, but I've run into a problem with setting gridy. I've already visited the GridBagLayout not obeying gridx and gridy and (unless I'm just stupid), that didn't help me. I used GridBagLayout with GridBagConstraints for statsPanel() and gridy worked fine.
Here's the problem: whenever I set gridy to the next grid in proficinciesAndSkillsPanel(), it's treated like I just changed gridx. My goal is to have one column with many rows, not one row with many columns. Thank you for your time
//this builds the jframe and sets the primary jpanel
private void buildComponents()
{
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mp = (JPanel)getContentPane();
mp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
mp.add(panelA(), gbc);
gbc.gridx = 1;
mp.add(new JButton("test"), gbc);
createMenuBar();
setVisible(true);
}
//this creates the first real panel that i'm currently working with
private JPanel panelA()
{
JPanel result = new JPanel();
result.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
//I left out the code for statsPanel() because that works fine
result.add(statsPanel(), gbc);
gbc.gridx = 1;
result.add(proficinciesAndSkillsPanel(), gbc);
return result;
}
//this builds the second half of the upper portion of panel A
private JPanel proficinciesAndSkillsPanel()
{
JPanel result = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1;
gbc.weighty = 1;
result.add(labeledTextField("Inspiration", inspirationField = new JTextField(2), null, 1), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
result.add(labeledTextField("Proficiency bonus", proficiencyField = new JTextField(2), null, 1),gbc);
gbc.gridx = 0;
gbc.gridy = 2;
result.add(labeledRadioField("Strength", strSTField = new JTextField(2), strRB = new JRadioButton()),gbc);
return result;
}
//this creates a JTextField with the appropriate label and a sub-JTextField
private JPanel labeledTextField(String str, JTextField jtf, JTextField bonjtf, int space)
{
JPanel result = new JPanel();
JPanel subResult = new JPanel();
result.setLayout(new FlowLayout());
result.add(new JLabel(str));
result.add(Box.createHorizontalStrut(space));
subResult.add(jtf);
jtf.setHorizontalAlignment(JTextField.CENTER);
try
{
subResult.add(bonjtf);
bonjtf.setHorizontalAlignment(JTextField.CENTER);
bonjtf.setEditable(false);
bonjtf.setText("+0");
}catch(NullPointerException e){}
jtf.addKeyListener(new JTF_Listener(){
public void update() {
String str2 = "";
try
{
int result = (Integer.parseInt(jtf.getText())-10)/2;
if(result >=0)
{
str2 += "+"+Integer.toString(result);
}
else
{
str2 += Integer.toString(result);
}
}catch(NumberFormatException nfe){}
bonjtf.setText(str2);
}
});
result.add(subResult);
return result;
}
//this does the same as labeledTextField, just with a radioButton
private JPanel labeledRadioField(String str, JTextField jtf, JRadioButton jrb)
{
JPanel result = new JPanel();
result.setLayout(new FlowLayout());
result.add(jrb);
result.add(jtf);
result.add(new JLabel(str));
jtf.setHorizontalAlignment(JTextField.CENTER);
jtf.setText("+0");
jtf.addKeyListener(new JTF_Listener(){
public void update(){
String str2 = "";
try
{
int result = Integer.parseInt(jtf.getText());
str2+= "+" + Integer.toString(result);
}catch(NumberFormatException nfe){}
jtf.setText(str2);
}
});
return result;
}
Not sure that this is your problem since you've not posted a valid MCVE (please correct this!), but here:
private JPanel proficinciesAndSkillsPanel()
{
JPanel result = new JPanel(); // ******** here *********
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1;
gbc.weighty = 1;
result.add(labeledTextField("Inspiration", inspirationField = new JTextField(2), null, 1), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
result.add(labeledTextField("Proficiency bonus", proficiencyField = new JTextField(2), null, 1),gbc);
gbc.gridx = 0;
gbc.gridy = 2;
result.add(labeledRadioField("Strength", strSTField = new JTextField(2), strRB = new JRadioButton()),gbc);
return result;
}
You're treating this result JPanel as if it uses GridBagLayout when in fact it's not, it's using JPanel's default FlowLayout
One confusing bit: you've got many JPanel variables that have been given the same name, result. In your code you do in fact call result.setLayout(new GridBagLayout()), but not for the JPanel that I show above, and this might be confusing you. I suggest that you avoid using the same variable names in your code as you're doing to avoid this confusion.
If you need more specific help, then you first, please tell us more of the details and show us your pertinent code as a valid minimal example program or MCVE. If you're sitting in our shoes, and are trying to understand someone else's confusing code, it makes a huge difference if they put the effort in to make that code compilable and runnable for us.
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);
I'm new to Swing and I want to create a table having this form:
So How to split a cell like the table shows?
Have you any useful links or tutorials or an idea?
This looks like a bowling score card to me. Based on that assumption, the number of columns is fixed, and the number of entries tends to be 6 or less. Since you likely won't need scrolling, I would recommend a fixed grid of components instead of a JTable.
This could easily be acheived using GridBagLayout. For the name, I'd use a JTextArea. For the 2 scoring cells for each frame, I'd use JTextFields. For the bottom 2-column-span component that holds the frame's score I'd probably use a JLabel.
Put all of this on a JPanel, and recreate the panel for each bowler.
EDIT:
Here's a quick mock-up just to show the concept. Not necessarily visually pretty, but I'll leave that as an exercise for the reader:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BowlingScoreCard implements Runnable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new BowlingScoreCard());
}
public void run()
{
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createScorecard(4), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JPanel createScorecard(int numPlayers)
{
JPanel p = new JPanel(new GridBagLayout());
p.add(new JLabel("Player"), gbc(0, 0, 1, 1));
for (int x = 1; x <= 10; x++)
{
p.add(new JLabel(Integer.toString(x)), gbc(x, 0, 1, 1));
}
for (int y = 1; y <= numPlayers; y++)
{
JTextArea textArea = new JTextArea(2, 10);
p.add(textArea, gbc(0, y, 1, 1));
for (int i = 1; i <= 9; i++)
{
p.add(createFrame(2), gbc(i, y, 1, 1));
}
p.add(createFrame(3), gbc(10, y, 1, 1));
}
return p;
}
private JPanel createFrame(int entries)
{
JLabel label = new JLabel(" ");
label.setBackground(Color.GRAY);
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
for (int i = 0; i < entries; i++)
{
p.add(new JTextField(3), gbc(i, 0, 1, 1));
}
p.add(label, gbc(0, 1, 2, 1));
return p;
}
private GridBagConstraints gbc(int x, int y, int colspan, int rowspan)
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = colspan;
gbc.gridheight = rowspan;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
return gbc;
}
}
I have a panel in which i have specified with a grid bag layout. I basically have 1 column and 4 rows. The labels are aligned to the center by default. How do i align them to the left?
private void addLabel(String name, int gridx, int gridy, int anchor ){
gbc.gridx=gridx;
gbc.gridy=gridy;
JLabel label=new JLabel(name);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbag.setConstraints(label, gbc);
panel1.add(label);
The caller lines are:
gbc=new GridBagConstraints();
gbag=new GridBagLayout();
panlel1.setLayout(gbag);
addLabel(" Exemption type", 0, 0,anchor );
try
JLabel myLabel = new JLabel("Fubar", SwingConstants.LEFT);
Or you could do the same on an already created JLabel by calling myLabel.setHorizontalAlignment(SwingConstants.LEFT);
edit: for example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagExample {
private static void createAndShowUI() {
String[] data = {"one", "two", "three", "four"};
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0; // **** comment this line out to see effect ****
gbc.weighty = 1.0; // **** comment this line out to see effect ****
for (int i = 0; i < data.length; i++) {
JLabel label = new JLabel(data[i]);
gbc.gridy = i;
panel.add(label, gbc);
}
JFrame frame = new JFrame("GridBagExample");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Here is how I solved this.
The important part is
gbc.anchor = GridBagConstraints.WEST;
The above is called right after you specify the layout cell you want and right before you add the component to the panel.
GridBagConstraints anchor
This field is used when the component is smaller than its display
area. It determines where, within the display area, to place the
component. ...
Below is basically how I implemented it.
public class ControlPanel extends JPanel{...
ControlPanel(){
this.setLayout(new GridBagLayout());
//create components
...
GridBagConstraints gbc = new GridBagConstraints();
//space components out a little
gbc.insets = new Insets(5,5,5,5);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(button_btn,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(spinner1_pnl,gbc);
gbc.gridx = 2;
gbc.gridy = 0;
this.add(spinner2_pnl,gbc);
gbc.gridx = 3;
gbc.gridy = 0;
this.add(checkbox1_chk,gbc);
gbc.gridx = 4;
gbc.gridy = 0;
this.add(checkbox2_chk,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3; //span 3 columns
gbc.anchor = GridBagConstraints.WEST;
this.add(results_lbl,gbc);
}
}
In this case I put a label below some other components, but most importantly that label is left (west) aligned within its cell.