Align JLabel to the left of the panel in a gridbaglayout - java

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.

Related

GridBagLayout not applying gridy changes

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.

JFrame center components

I was wondering how to center my components, I found the gridBagLayout but I couldn't find a way to have it bigger than it is : my buttons are too small.
Part of my code :
private void addMainButtons() {
JPanel container = new JPanel() {
private static final long serialVersionUID = -424395301619105440L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension dim = this.getSize();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.setColor(Color.BLACK);
String s = format.format(date);
g.drawString(s, (int) ((dim.getWidth() - s.length() - 80) / 2), 20);
}
};
container.setBackground(new Color(109, 69, 60));
JButton productsButton = new JButton("Produits");
productsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(frame, pages[1]);
}
});
productsButton.setAlignmentY(Component.CENTER_ALIGNMENT);
productsButton.setAlignmentX(Component.CENTER_ALIGNMENT);
// Creating grid
container.setPreferredSize(new Dimension(400, 600));
container.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
container.add(productsButton, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
container.add(new JButton("Entrée"), gbc);
gbc.gridx = 1;
container.add(new JButton("Sortie"), gbc);
mainPage.setLayout(new BorderLayout());
mainPage.add(container, BorderLayout.CENTER);
// End of main page
}
GridBagLayout is really difficult to use, is there another way to center components ? I could use NestedLayouts but I don't know how.
You can use weightx and/or weighty to effect the amount of space the components will occupy, for example, if I do
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 1;
gbc.weighty = 1;
container.add(productsButton, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
container.add(new JButton("Entrée"), gbc);
gbc.gridx = 1;
container.add(new JButton("Sortie"), gbc);
I can generate this...
You could use two containers, one holding a JLabel which shows the date and one which contains the buttons, but I doubt that's what you're really after.
You can use ipadx and ipady which adds the amount to the components preferred size
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.ipadx = 40;
gbc.ipady = 40;
container.add(productsButton, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
container.add(new JButton("Entrée"), gbc);
gbc.gridx = 1;
container.add(new JButton("Sortie"), gbc);
which, when included with your existing constraints, allows you to "grow" the buttons a bit.
Try below code for increasing size of button while adding every components to gridbagconstraints. Change the value of weightx/weighty as you want.
gbc.weightx = 1.0;
gbc.weighty = 1.0;
To give more spaces between components, use below code while adding every components to gridbagconstraints.
gbc.insets = new Insets(2, 2, 2, 2);
According to my knowledge, you used correct way to center components. It can also be done by other layout but it may be little bit difficult.

GridBagLayout content not aligning to the right of JPanel

I have a JFrame (BorderLayout) holding a JPanel(GridBagLayout) in the South position. The JPanel border fills the screen horizontally (as I wanted it to), and so does the content within it (I don't want that).
It's much easier to visualize, so I did in Photoshop what I couldn't figure out in Java...
I made this in photoshop to demonstrate what I WANT to happen:
This is what my code produces:
Here's the code I'm using:
private void loadTags(String filePath)
{
Map<String, ArrayList<String>> fileTags;
try
{
fileTags = PowerPointManipulator.getTagsFromFile(filePath);
}
catch (IOException e)
{
System.err.println("Could not open Powerpoint File");
e.printStackTrace();
return;
}
tag_listener = new TagButtonListener();
pnl_tags = new JPanel();
pnl_tags.setBackground(new Color(0, 0, 0, 0));
pnl_tags.setLayout(new GridBagLayout());
pnl_tags.setAlignmentX(LEFT_ALIGNMENT);
brd_tags = new TitledBorder("Tags");
brd_tags.setTitleColor(Color.WHITE);
brd_tags.setBorder(new LineBorder(Color.WHITE));
pnl_tags.setBorder(brd_tags);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(0, 0, 2, 15);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
int col = 0;
for (String key : fileTags.keySet())
{
ArrayList<String> vals = fileTags.get(key);
gbc.gridwidth = 2;
gbc.gridx = col;
gbc.gridy = 0;
JToggleButton tempButton = new JToggleButton(key);
tempButton.setOpaque(false);
tempButton.addActionListener(tag_listener);
tempButton.setFocusable(false);
pnl_tags.add(tempButton, gbc);
int row = 1;
for (String val : vals)
{
tempButton = new JToggleButton(val);
tempButton.setOpaque(false);
tempButton.addActionListener(tag_listener);
tempButton.setFocusable(false);
gbc.gridwidth = 1;
gbc.gridy = row;
pnl_tags.add(tempButton, gbc);
row++;
}
col += 2;
}
contentPane.add(pnl_tags, BorderLayout.PAGE_END);
}
If I remove the "weight" options, then I get the proper layout, except that the buttons are centered within the JPanel.
I feel like I'm so close, but I can't get the exact right settings! Any help is much appreciated!
GridBagConstraints#weightx and GridBagConstraints#weighty will cause the component to occupy all the remaining space left over after all the other components have been laid out, GridBagConstraints#fill will cause the component to fill the available space of the cell it resides in based on the value you supply so,
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
is doing exactly what you asked it to.
You could try something like...
List<String> tags = new ArrayList<>(25);
tags.add("example");
tags.add("objective");
tags.add("motivation");
tags.add("summary");
tags.add("c");
tags.add("*");
tags.add("*");
tags.add("*");
tags.add("cs");
JPanel tagPane = new JPanel(new GridBagLayout());
tagPane.setBorder(new TitledBorder("Tags"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
for (String tag : tags) {
tagPane.add(new JToggleButton(tag), gbc);
gbc.gridx--;
if (gbc.gridx < 0) {
gbc.gridx = 3;
gbc.gridy++;
}
}
Which results in something like...
Okay, so that's a little better, but they are grouped in the center!
Well, you could set it so each right hand side column has a weightx of 1, for example...
gbc.gridx--;
if (gbc.gridx < 0) {
gbc.gridx = 3;
gbc.gridy++;
gbc.weightx = 1;
} else {
gbc.weightx = 0;
}
Or add a "filler" component to the right of all the other components...
for (String tag : tags) {
tagPane.add(new JToggleButton(tag), gbc);
gbc.gridx--;
if (gbc.gridx < 0) {
gbc.gridx = 3;
gbc.gridy++;
}
}
JLabel filler = new JLabel();
gbc.gridx = 4;
gbc.gridy = 0;
gbc.weightx = 1;
tagPane.add(filler, gbc);
Either way, you end up with something like....
Take a closer look at How to Use GridBagLayout for more details

How to take these labels in exactly required position

I am trying to create a small GUI with some lables and txtAreas. I did it by using absolute positioning, but I want to go on gridbag layout. I am trying from last 3 days, but couldnt get these lables as required position. either stucking in the middle around, or they stucking near the border. Please help to get them in these positions.
public void initUIPanel()
{
jf = new JFrame();
jf.setTitle("Mortgage Calculator");
jf.setLocation(100,200);
jf.setSize(400,500);
jf.setVisible (true);
//jf.setResizable(false);
JPanel panel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
loanAmount = new JTextField(15);
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(loanAmount, gbc);
panel.add(loanAmount);
loanTerm = new JTextField(15);
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(loanTerm, gbc);
panel.add(loanTerm);
amount = new JLabel("Loan Amount");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(amount, gbc);
panel.add(amount);
term= new JLabel("Loan Term");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(term, gbc);
panel.add(term);
currency = new JLabel ("AUD");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(currency, gbc);
panel.add(currency);
numOfYear = new JLabel ("Year");
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(numOfYear, gbc);
panel.add(numOfYear);
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );
txtResult = new JTextArea();
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(txtResult, gbc);
panel.add(txtResult);
jf.add(panel,"Center");
//panel.setBounds(200,200,200,20);
jf.setVisible(true);
}
It is giving everything in 2 lines. all messed.
What I want is
First Line: Loan Amount: ............(txt Area).... "AUD"
Second LIne: Loan Term: .............(Txt Area......Years
Then Txtbox
Thank you
You haven't set the layout of the panel:
panel.setLayout(gbl);
And, as already said in the comments, all the components have the same gridx and gridy, which is obviously not right.
Here's a complete example which, if I understand correctly, does what you want:
import javax.swing.*;
import java.awt.*;
public class GblTest extends JFrame {
public GblTest() {
add(createPanel(), BorderLayout.NORTH);
}
private JPanel createPanel() {
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.BASELINE_LEADING;
p.add(new JLabel("Loan amount"), c);
c.gridx++;
p.add(new JTextField(15), c);
c.gridx++;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
p.add(new JLabel("AUD"), c);
c.gridx = 0;
c.gridy++;
c.fill = GridBagConstraints.NONE;
c.weightx = 0.0;
p.add(new JLabel("Loan term"), c);
c.gridx++;
p.add(new JTextField(15), c);
c.gridx++;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
p.add(new JLabel("Years"), c);
return p;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GblTest test = new GblTest();
test.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
}
});
}
}

JRadio Buttons are "Hiding" in GridBagLayout

Please have a look at the following code
package normal;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Form extends JFrame
{
private JLabel heightLabel, weightLabel, waistLabel, neckLabel, hipsLabel,genderLabel,valuesLabel,bfPercentageLabel;
private JLabel logoLabel;
private ImageIcon logo;
private JTextField heightTxt, weightTxt, waistTxt, neckTxt, hipsTxt;
private JRadioButton maleRadio, femaleRadio, inchesRadio, cmRadio;
private ButtonGroup genderGroup, valuesGroup;
private JComboBox percentageCombo;
private JPanel centerPanel, northPanel, southPanel;
public Form()
{
//Declaring instance variables
heightLabel = new JLabel("Height: ");
weightLabel = new JLabel("Weight: ");
waistLabel = new JLabel("Waist: ");
neckLabel = new JLabel("Neck: ");
hipsLabel = new JLabel("Hips: ");
genderLabel = new JLabel("Gender: ");
valuesLabel = new JLabel("Values in: ");
logoLabel = new JLabel();
logo = new ImageIcon(getClass().getResource("/images/calc_logo_final_2_edit.gif"));
logoLabel.setIcon(logo);
heightTxt = new JTextField(10);
weightTxt = new JTextField(10);
waistTxt = new JTextField(10);
neckTxt = new JTextField(10);
hipsTxt = new JTextField(10);
maleRadio = new JRadioButton("Male");
femaleRadio = new JRadioButton("Female");
genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
inchesRadio = new JRadioButton("Inches");
cmRadio = new JRadioButton("Centimeters");
valuesGroup = new ButtonGroup();
valuesGroup.add(inchesRadio);
valuesGroup.add(cmRadio);
percentageCombo = new JComboBox();
percentageCombo.addItem("No Value is Set");
this.add(createNorthPanel(),"North");
this.add(createCenterPanel(),"Center");
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createNorthPanel()
{
northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(logoLabel);
return northPanel;
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
centerPanel.setLayout(gbl);
//creating a jpanel for gender radio buttons
JPanel genderPanel = new JPanel();
genderPanel.setLayout(new FlowLayout());
genderPanel.add(genderLabel);
genderPanel.add(maleRadio);
genderPanel.add(femaleRadio);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(heightLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(heightTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(weightLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(weightTxt,gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(waistLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(waistTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(neckLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(neckTxt,gbc);
gbc.gridx = 5;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(hipsLabel,gbc);
gbc.gridx = 6;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(hipsTxt,gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(genderLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,5,0,0);
centerPanel.add(maleRadio,gbc);
gbc.gridx = 3;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,-10,0,0);
centerPanel.add(femaleRadio,gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(50,5,0,0);
centerPanel.add(valuesLabel,gbc);
return centerPanel;
}
}
As you can see, the JRadio button "female" is hiding a part of it, and once you move your cursor, it shows up completely. I guess this is happening because it is using minus spacing in "insets".
However I did it like that to reduce the gap between 2 radio buttons. Male is in gridx = 2, and female is in gridx = 3, which is a massive space between the buttons.So I used minus space in insets to reduce the space, unfortunately it came like this.
I tried adding the JLabel, maleRadio and femaleRadio into a seperate JPanel which is having flowlayout, and put it into gbc.gridx = 2; gbc.gridy = 3;. It made everything worst by matching all the cells in gridy = 3 into the width of new JPanel.
Please help me to reduce the gap between these 2 JRadio buttons, without having any issue. Thank you.
Dont extend JFrame rather create an instance and use that.
Also I see you add your radio buttons to a panel but you dont add the panel rather you re-add the radio buttons to centerpanel? choose one way lose the other (though I think this might have occurred in trying to mend the problem?)
An SSCCE most importantly is compilable (via correct syntax and no compile error) and runnable (via a main method and no runtime exceptions (unless thats the problem :P) - like your reading of the image - please find a way to include resources i.e link to an URL with the logo or make a method return a simple image the same size as logo or simply leave it out).
The problem is here:
gbc.gridx = 3;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15, -10, 0, 0);
centerPanel.add(femaleRadio, gbc);
-10 should definitely not be there (maybe typo?) as this will cause it to overlap or in this case underlap another component, rather use anything greater than or equal to 0:
gbc.gridx = 3;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15, 10, 0, 0);
centerPanel.add(femaleRadio, gbc);
which would give us:
UPDATE:
Also it is important to note GridBagContsraints like gridx etc start at 0 and not 1.
+1 to #Gagandeeps balis comment on re-using values which have been set already and are the same in GridBagConstraints, here is your code with all talked about fixes:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
class Form {
private JLabel heightLabel, weightLabel, waistLabel, neckLabel, hipsLabel, genderLabel, valuesLabel, bfPercentageLabel;
private JLabel logoLabel;
private ImageIcon logo;
private JTextField heightTxt, weightTxt, waistTxt, neckTxt, hipsTxt;
private JRadioButton maleRadio, femaleRadio, inchesRadio, cmRadio;
private ButtonGroup genderGroup, valuesGroup;
private JComboBox percentageCombo;
private JPanel centerPanel, northPanel, southPanel;
public Form() {
//Declaring instance variables
heightLabel = new JLabel("Height: ");
weightLabel = new JLabel("Weight: ");
waistLabel = new JLabel("Waist: ");
neckLabel = new JLabel("Neck: ");
hipsLabel = new JLabel("Hips: ");
genderLabel = new JLabel("Gender: ");
valuesLabel = new JLabel("Values in: ");
logoLabel = new JLabel();
//logo = new ImageIcon(getClass().getResource("/images/calc_logo_final_2_edit.gif"));
//logoLabel.setIcon(logo);
heightTxt = new JTextField(10);
weightTxt = new JTextField(10);
waistTxt = new JTextField(10);
neckTxt = new JTextField(10);
hipsTxt = new JTextField(10);
maleRadio = new JRadioButton("Male");
femaleRadio = new JRadioButton("Female");
genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
inchesRadio = new JRadioButton("Inches");
cmRadio = new JRadioButton("Centimeters");
valuesGroup = new ButtonGroup();
valuesGroup.add(inchesRadio);
valuesGroup.add(cmRadio);
percentageCombo = new JComboBox();
percentageCombo.addItem("No Value is Set");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createNorthPanel(), "North");
frame.add(createCenterPanel(), "Center");
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private JPanel createNorthPanel() {
northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(logoLabel);
return northPanel;
}
private JPanel createCenterPanel() {
centerPanel = new JPanel(new GridBagLayout());
GridBagLayout gbl = new GridBagLayout();
centerPanel.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15, 5, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
centerPanel.add(heightLabel, gbc);
gbc.gridx = 1;
centerPanel.add(heightTxt, gbc);
gbc.gridx = 2;
centerPanel.add(weightLabel, gbc);
gbc.gridx = 3;
centerPanel.add(weightTxt, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
centerPanel.add(waistLabel, gbc);
gbc.gridx = 1;
centerPanel.add(waistTxt, gbc);
gbc.gridx = 2;
centerPanel.add(neckLabel, gbc);
gbc.gridx = 3;
centerPanel.add(neckTxt, gbc);
gbc.gridx = 4;
centerPanel.add(hipsLabel, gbc);
gbc.gridx = 5;
centerPanel.add(hipsTxt, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
centerPanel.add(genderLabel, gbc);
gbc.gridx = 1;
centerPanel.add(maleRadio, gbc);
gbc.gridx = 2;
centerPanel.add(femaleRadio, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(50, 5, 0, 0);
centerPanel.add(valuesLabel, gbc);
return centerPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Form();
}
});
}
}

Categories