I was trying to make a keyboard layout, where one can specify the buttons' width. Therefore, I made an attempt with GridBagLayout but without success.
To illustrate my problem I did a simple example, where I expected to obtain this (Button2, Button4, Button5, Button6):
but instead I get Button4 and Button6 of double width.
The code is:
package views;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestLayout extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TestLayout().setVisible(true);
}
});
}
public TestLayout() {
JButton btn;
setBounds(0, 0, 444, 111);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 1;//ROW 1
btn = new JButton("Button 1");gbc.gridx = 0;gbc.gridwidth = 1;add(btn, gbc);
btn = new JButton("Button 2");gbc.gridx = 1;gbc.gridwidth = 2;add(btn, gbc);
btn = new JButton("Button 3");gbc.gridx = 3;gbc.gridwidth = 1;add(btn, gbc);
btn = new JButton("Button 4");gbc.gridx = 4;gbc.gridwidth = 2;add(btn, gbc);
gbc.gridy = 2;//ROW 2
btn = new JButton("Button 5");gbc.gridx = 0;gbc.gridwidth = 2;add(btn, gbc);
btn = new JButton("Button 6");gbc.gridx = 2;gbc.gridwidth = 2;add(btn, gbc);
btn = new JButton("Button 7");gbc.gridx = 4;gbc.gridwidth = 1;add(btn, gbc);
btn = new JButton("Button 8");gbc.gridx = 5;gbc.gridwidth = 1;add(btn, gbc);
}
}
Moreover, my goal is to define the keyboard something like this, with no correlation between rows, which I couldn't achieved with this Layout manager:
I took this matter over to Why does this GridBagLayout not appear as planned? & camickr solved it using a dummy row of components, each 1 gridwidth wide.
These 2 images show:
At the bottom, the 'minimalist' version of the code that uses a 1px tall transparent image.
At the top, the more obvious version that uses a solid black image that is 5 px tall.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class KeyBoardLayout {
private JComponent ui = null;
KeyBoardLayout(boolean lowImpact) {
initUI(lowImpact);
}
public void initUI(boolean lowImpact) {
if (ui != null) {
return;
}
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = .5;
gbc.weighty = .5;
gbc.fill = GridBagConstraints.BOTH;
/* This code adds a dummy (invisible) row of components, 1 per
single gridwidth column. It has the effect of forcing the GBL width
to the size we would expect, proportional to each gridwidth assigned.
The problem with this (simple) approach is that the perfect
width will change according to PLAF and the content/preferred
size of the visible components. */
// TODO! improve on use of 'magic numbers'
int w = 30; // adjust width per requirement
int h = lowImpact ? 1 : 5; // 1 for small height/border, 5 for large
// TYPE_INT_RGB for black
// TYPE_INT_ARGB for invisible
int t = lowImpact ?
BufferedImage.TYPE_INT_ARGB :
BufferedImage.TYPE_INT_RGB;
// an icon for the dummy row
ImageIcon ii = new ImageIcon(new BufferedImage(w, h, t));
ui.setBorder(new CompoundBorder(
ui.getBorder(), new EmptyBorder(0, 0, h, 0)));
// put a 'padding cell' in each column of the top row
// to force the layout to respect each individual column
for (int i = 0; i < 22; i++) {
gbc.gridx = i;
gbc.gridy = 4;
ui.add(new JLabel(ii));
}
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
ui.add(new JButton("1,1 (3)"), gbc);
gbc.gridx = 3;
gbc.gridwidth = 2;
ui.add(new JButton("2,1 (2)"), gbc);
gbc.gridx = 5;
ui.add(new JButton("3,1 (2)"), gbc);
gbc.gridx = 7;
ui.add(new JButton("4,1 (2)"), gbc);
gbc.gridx = 9;
ui.add(new JButton("5,1 (2)"), gbc);
gbc.gridx = 11;
ui.add(new JButton("6,1 (2)"), gbc);
gbc.gridx = 13;
ui.add(new JButton("7,1 (2)"), gbc);
gbc.gridx = 15;
gbc.gridwidth = 3;
ui.add(new JButton("8,1 (3)"), gbc);
gbc.gridx = 18;
gbc.gridwidth = 4;
ui.add(new JButton("9,1 (4)"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
ui.add(new JButton("1,2 (4)"), gbc);
gbc.gridx = 4;
gbc.gridwidth = 2;
ui.add(new JButton("2,2 (2)"), gbc);
gbc.gridx = 6;
ui.add(new JButton("3,2 (2)"), gbc);
gbc.gridx = 8;
ui.add(new JButton("4,2 (2)"), gbc);
gbc.gridx = 10;
ui.add(new JButton("5,2 (2)"), gbc);
gbc.gridx = 12;
ui.add(new JButton("6,2 (2)"), gbc);
gbc.gridx = 14;
ui.add(new JButton("7,2 (2)"), gbc);
gbc.gridx = 16;
ui.add(new JButton("8,2 (2)"), gbc);
gbc.gridx = 18;
gbc.gridwidth = 4;
ui.add(new JButton("9,2 (4)"), gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 5;
ui.add(new JButton("1,3 (5)"), gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
ui.add(new JButton("2,3 (2)"), gbc);
gbc.gridx = 7;
ui.add(new JButton("3,3 (2)"), gbc);
gbc.gridx = 9;
ui.add(new JButton("4,3 (2)"), gbc);
gbc.gridx = 11;
ui.add(new JButton("5,3 (2)"), gbc);
gbc.gridx = 13;
ui.add(new JButton("6,3 (2)"), gbc);
gbc.gridx = 15;
ui.add(new JButton("7,3 (2)"), gbc);
gbc.gridx = 17;
ui.add(new JButton("8,3 (2)"), gbc);
gbc.gridx = 19;
gbc.gridwidth = 3;
ui.add(new JButton("9,3 (3)"), gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 3;
ui.add(new JButton("1,4 (3)"), gbc);
gbc.gridx = 3;
ui.add(new JButton("2,4 (3)"), gbc);
gbc.gridx = 6;
gbc.gridwidth = 10;
ui.add(new JButton("3,4 (10)"), gbc);
gbc.gridx = 16;
gbc.gridwidth = 3;
ui.add(new JButton("4,4 (3)"), gbc);
gbc.gridx = 19;
ui.add(new JButton("5,4 (3)"), gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 1;
}
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) {
}
for (int ii = 0; ii < 2; ii++) {
KeyBoardLayout o = new KeyBoardLayout(ii==0);
JFrame f = new JFrame("Keyboard Layout");
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);
}
}
Related
I'm having major issues aligning the components in GridBagLayout, yes I've read the tutorial by Oracle and tried changing the weightx.
This is how it looks like currently :
Basically what I need to achieve is:
JTextFields "Nome" and "Filiação" to stretch all the way to the left, just like "Idade" and "Turma"
Bottom JButtons to be the same size, aligned in the middle.
I hope someone can point what I'm missing here.
Here's a sorta SSCCE:
package test1;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test1 {
public static void main(String[] args) {
JFrame jf = new JFrame("Test");
JPanel jp = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
JLabel labelNome = new JLabel("Nome:");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
jp.add(labelNome, gbc);
JTextField tfNome = new JTextField();
gbc.gridx = 1;
gbc.ipadx = 50;
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(tfNome, gbc);
JLabel labelIdade = new JLabel("Idade :");
gbc.ipadx = 0;
gbc.gridx = 2;
gbc.fill = GridBagConstraints.NONE;
jp.add(labelIdade, gbc);
JTextField tfIdade = new JTextField();
gbc.gridx = 3;
gbc.ipadx = 50;
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(tfIdade, gbc);
JLabel labelEndereco = new JLabel("Endereço :");
gbc.ipadx = 0;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
jp.add(labelEndereco, gbc);
JTextField tfEndereco = new JTextField();
gbc.ipadx = 50;
gbc.gridx = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(tfEndereco, gbc);
JLabel labelFiliacao = new JLabel("Filiação :");
gbc.ipadx = 0;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.BOTH;
jp.add(labelFiliacao, gbc);
JTextField tfFiliacao = new JTextField();
gbc.gridx = 1;
gbc.ipadx = 50;
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(tfFiliacao, gbc);
JLabel labelTurma = new JLabel("Turma :");
gbc.ipadx = 0;
gbc.gridx = 2;
gbc.fill = GridBagConstraints.BOTH;
jp.add(labelTurma, gbc);
JTextField tfTurma = new JTextField();
gbc.gridx = 3;
gbc.ipadx = 50;
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(tfTurma, gbc);
JLabel labelDisciplina = new JLabel("Disciplina :");
gbc.ipadx = 0;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
jp.add(labelDisciplina, gbc);
JTextField tfDisciplina = new JTextField();
gbc.ipadx = 50;
gbc.ipady = 0;
gbc.gridx = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(tfDisciplina, gbc);
JButton adicionaDisciplina = new JButton("Adicionar disciplina");
gbc.ipadx = 0;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 4;
jp.add(adicionaDisciplina, gbc);
JButton limparDisciplina = new JButton("Limpar lista de disciplinas");
gbc.gridx = 2;
jp.add(limparDisciplina, gbc);
JButton botaoSalvar = new JButton("Salvar");
gbc.gridx = 0;
gbc.gridy = 5;
jp.add(botaoSalvar, gbc);
JButton botaoCancelar = new JButton("Cancelar");
gbc.gridx = 2;
jp.add(botaoCancelar, gbc);
jf.setSize(500, 550);
jf.add(jp);
jf.setVisible(true);
}
}
JTextFields "Nome" and "Filiação" to stretch all the way to the left, just like "Idade" and "Turma"
Don't know what that means. They are aligned to the left just like the other text fields in that second column.
They may not appear as far left as the other text fields because the "Endereco" label length is longer, so the second column can only start where that ends.
If you want the text fields to have the same size then you need to specify the size of your text field and the GridBagLayout will respect the size. You do this by specifying the columns in the text field when you create the text field:
JTextField tfNome = new JTextField(10);
I have a problem with getting the GridBagLayout work as expected.
The gridy of the GridBagConstraints didn't seem to function as expected at all for atomIndexLabel (JLabel), atomIndexExample (JLabel) and atomIndexAddField (JTextField). I want to align them to approximately the middle of the table, but when running, they stick to the top, just like gridy is set to 0, 1 and 2.
I tried to add an emptyElement, but it didn't work. My code is below. Any suggestions?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.DefaultTableModel;
public class Test extends JPanel {
private static final long serialVersionUID = -7810531559762481489L;
private JLabel atomIndexLabel, atomIndexExample, atomIndexNotification;
private JTextField atomIndexAddField;
private JButton atomIndexAddButton, atomIndexRemoveButton;
private AtomIndexButtonListener atomIndexButtonListener;
private JTable atomIndexTable;
private JScrollPane atomIndexTableScrollPane;
private DefaultTableModel atomIndexTableModel;
public Test() {
this.atomIndexLabel = new JLabel("Input one or multiple atom indexs:");
this.atomIndexExample = new JLabel("Example: 1 2 3 4 5");
this.atomIndexAddField = new JTextField(20);
this.atomIndexAddButton = new JButton("Add Atom Index");
this.atomIndexTable = new JTable(1, 1);
this.atomIndexTableModel = new DefaultTableModel() {
private static final long serialVersionUID = -6458638313466319330L;
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
this.atomIndexTable.setModel(atomIndexTableModel);
this.atomIndexTableModel.addColumn("Atom_Index");
this.atomIndexTableScrollPane = new JScrollPane(atomIndexTable);
this.atomIndexTableScrollPane.setPreferredSize(new Dimension(100, 170));
this.atomIndexRemoveButton = new JButton("Remove Selected");
this.atomIndexNotification = new JLabel("No input atom index");
this.atomIndexNotification.setHorizontalAlignment(JLabel.CENTER);
setupLayout();
this.atomIndexButtonListener = new AtomIndexButtonListener();
this.atomIndexAddButton.addActionListener(atomIndexButtonListener);
this.atomIndexRemoveButton.addActionListener(atomIndexButtonListener);
this.setBorder(new TitledBorder("Atom Index Input"));
}
private void setupLayout() {
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
/*JComponent emptyElement = new JLabel("");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 6;
gbc.anchor = GridBagConstraints.LAST_LINE_START;
this.add(emptyElement, gbc);*/
gbc.gridx = 0;
gbc.gridy = 6;
gbc.gridwidth = 4;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
this.add(atomIndexLabel, gbc);
gbc.gridx = 0;
gbc.gridy = 7;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
this.add(atomIndexExample, gbc);
gbc.gridx = 0;
gbc.gridy = 8;
gbc.gridwidth = 4;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
this.add(atomIndexAddField, gbc);
gbc.gridx = 0;
gbc.gridy = 11;
gbc.gridwidth = 4;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(10, 0, 0, 0);
this.add(atomIndexAddButton, gbc);
gbc.gridx = 5;
gbc.gridy = 0;
gbc.gridwidth = 6;
gbc.gridheight = 12;
gbc.insets = new Insets(10, 10, 0, 0);
this.add(atomIndexTableScrollPane, gbc);
gbc.gridx = 5;
gbc.gridy = 12;
gbc.gridwidth = 6;
gbc.gridheight = 1;
gbc.insets = new Insets(10, 10, 0, 0);
this.add(atomIndexRemoveButton, gbc);
gbc.gridx = 0;
gbc.gridy = 13;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.insets = new Insets(20, 0, 0, 0);
this.add(atomIndexNotification, gbc);
}
private class AtomIndexButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("For Test only");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new Test());
frame.setSize(1000, 900);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Using Java, I am creating a form with GridBagLayout. the GUI is inside a JPanel, which is inside a scrollPane which is added to a JFrame.
I want the JPanel with the GUI to be a fixed size to prevent the form being stretched, however, I would like the JScrollPanel to be resizable for the user's preference. (Similar to MS Paint, with the canvas being my JPanel). The reason I want to prevent the form from being stretched is because I want it to print and from the way I have it now, the printed form prints pretty much the way I want it, but alters unfavorably if the frame as been resized prior to printing.
Perhaps my problem is better to be solved in the way I print, but the problem is that I have never dealt with this level of printing before and was unable to find similar questions/tutorials to help me solve my problem. The direction I am going may be "the poor man's way" of doing it, but its the only one that makes sense to me right now, I'm a fairly novice Java programmer.
FrontierMain.java
public class FrontierMain {
public FrontierMain(){
JFrame frame = new JFrame();
frame.setTitle("Frontier Insulation Labor Record Tool");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
LaborRecordPanel recordPanel = new LaborRecordPanel();
frame.add(recordPanel.scrollPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
FrontierMain fm = new FrontierMain();
}
});
System.out.println("Hello, World");
}
}
LaborRecordPanel.java
public class LaborRecordPanel implements
Printable, ActionListener {
private Color shade = new Color(201,201,201); // color for shaded cells
private JLabel dateSpace[] = new JLabel[7];
private JLabel grandTotalSpace = new JLabel();
private JLabel locAndDescSpace = new JLabel();
private JLabel personnelSpace[] = new JLabel[10]; // empty cells
private JLabel calendarGridLines[] = new JLabel[300]; //empty labels for gridlines
private ImageIcon logoIcon = new ImageIcon("Images/fici_logo1.jpg");
private JLabel logoLabel = new JLabel(logoIcon);
private JLabel authorizedBy = new JLabel("AUTHORIZED BY:");
private JLabel toCertify = new JLabel("THIS IS TO CERTIFY THAT THE ABOVE LABOR HAS BEEN PERFORMED.");
private JLabel laborRecordNO = new JLabel("NO.");
private JLabel nameOfJob = new JLabel("NAME OF JOB:");
private JLabel customerPO = new JLabel("CUSTOMER PO #:");
private JLabel contractNO = new JLabel("CONTRACT NO.");
private JLabel weekEnding = new JLabel("WEEK ENDING");
private JLabel personnelList = new JLabel("<html>LIST SUPERVISION &<br> CRAFT LABOR BELOW:</html>");
private JLabel locAndDescriptionLabel = new JLabel("LOCATION AND DESCRIPTION:");
private JLabel personnelTitle = new JLabel("TITLE");
private JLabel supt = new JLabel("SUPT.");
private JLabel foreman = new JLabel("FOREMAN");
private JLabel[] mechanic= new JLabel[8];
private JLabel calendarTitle = new JLabel("NUMBER OF HOURS WORKED # SITE");
private JLabel dayHeading = new JLabel("DAY");
private JLabel dateHeading = new JLabel("DATE");
private JLabel[] ot2 = new JLabel[10];
private JLabel[] ot1 = new JLabel[10];
private JLabel[] st = new JLabel[10];
private JLabel mon = new JLabel("MON");
private JLabel tues = new JLabel("TUES");
private JLabel wed = new JLabel("WED");
private JLabel thur = new JLabel("THUR");
private JLabel fri = new JLabel("FRI");
private JLabel sat = new JLabel("SAT");
private JLabel sun = new JLabel("SUN");
private JLabel totalHours = new JLabel("<html>TOTAL<br> HOURS</html>");
private JLabel ratePerHour = new JLabel("<html>RATE<br> PER<br> HOUR</html>");
private JLabel totalAmount = new JLabel("<html>TOTAL<br> AMOUNT</html>");
private JLabel grandTotal = new JLabel("TOTAL");
JPanel rp = new JPanel();
JScrollPane scrollPane = new JScrollPane(rp);
LaborRecordPanel(){
rp.setPreferredSize(new Dimension(1295,1830 ));
rp.setMinimumSize(new Dimension(1295,1830 ));
rp.setMaximumSize(new Dimension(1295,1830 ));
scrollPane.setPreferredSize(new Dimension(900,700 ));
scrollPane.getVerticalScrollBar().setUnitIncrement(16); //increase the scroll speed
for (int i = 0; i <= 7; i++) mechanic[i] = new JLabel("MECHANIC"); // create mechanic labels
for (int i = 0; i <= 9; i++) //create labels for work time
{
ot2[i] = new JLabel("OT-2");
ot1[i] = new JLabel("OT-1");
st[i] = new JLabel("S.T.");
}
//create empty labels for gridlines
for (int i = 0; i <= 9; i++) personnelSpace[i] = new JLabel();
for (int i = 0; i <= 6; i++) dateSpace[i] = new JLabel();
for (int i = 0; i <= 299; i++) calendarGridLines[i] = new JLabel();
GridBagLayout gridbag = new GridBagLayout();
rp.setBackground(Color.WHITE);
rp.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
GridBagConstraints gbc = new GridBagConstraints();
rp.setLayout(gridbag);
//gbc.insets = new Insets(5, 5, 5, 5);
//row 0////////////////////////////////////////////////////////////
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 10;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
laborRecordNO.setHorizontalAlignment(JLabel.CENTER);
laborRecordNO.setFont(new Font("Dialog", Font.PLAIN, 18));
gridbag.setConstraints(laborRecordNO, gbc);
rp.add(laborRecordNO, gbc);
//row 1////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 13;
gridbag.setConstraints(logoLabel, gbc);
rp.add(logoLabel, gbc);
//row 2////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridheight = 1;
gbc.gridwidth = 1;
nameOfJob.setFont(nameOfJob.getFont().deriveFont(18.0f));
gridbag.setConstraints(nameOfJob, gbc);
rp.add(nameOfJob, gbc);
gbc.gridx = 6;
gbc.gridy = 2;
gbc.gridheight = 1;
gbc.gridwidth = 3;
contractNO.setFont(contractNO.getFont().deriveFont(18.0f));
gridbag.setConstraints(contractNO, gbc);
rp.add(contractNO, gbc);
//row 3////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridheight = 1;
gbc.gridwidth = 1;
customerPO.setFont(customerPO.getFont().deriveFont(18.0f));
gridbag.setConstraints(customerPO, gbc);
rp.add(customerPO, gbc);
gbc.gridx = 6;
gbc.gridy = 3;
gbc.gridheight = 1;
gbc.gridwidth = 3;
weekEnding.setFont(weekEnding.getFont().deriveFont(18.0f));
gridbag.setConstraints(weekEnding, gbc);
rp.add(weekEnding, gbc);
//row 4////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
personnelList.setHorizontalAlignment(JLabel.CENTER);
personnelList.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
personnelList.setFont(personnelList.getFont().deriveFont(18.0f));
gridbag.setConstraints(personnelList, gbc);
rp.add(personnelList, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
personnelTitle.setHorizontalAlignment(JLabel.CENTER);
personnelTitle.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK));
personnelTitle.setFont(personnelTitle.getFont().deriveFont(18.0f));
gridbag.setConstraints(personnelTitle, gbc);
rp.add(personnelTitle, gbc);
gbc.gridx = 2;
gbc.gridy = 4;
gbc.gridwidth = 8;
gbc.gridheight = 1;
calendarTitle.setHorizontalAlignment(JLabel.CENTER);
calendarTitle.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Color.BLACK));
calendarTitle.setFont(calendarTitle.getFont().deriveFont(18.0f));
gridbag.setConstraints(calendarTitle, gbc);
rp.add(calendarTitle, gbc);
gbc.gridx = 10;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
totalHours.setHorizontalAlignment(JLabel.CENTER);
totalHours.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
totalHours.setFont(totalHours.getFont().deriveFont(18.0f));
gridbag.setConstraints(totalHours, gbc);
rp.add(totalHours, gbc);
gbc.gridx = 11;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
ratePerHour.setHorizontalAlignment(JLabel.CENTER);
ratePerHour.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK));
ratePerHour.setFont(ratePerHour.getFont().deriveFont(18.0f));
gridbag.setConstraints(ratePerHour, gbc);
rp.add(ratePerHour, gbc);
gbc.gridx = 12;
gbc.gridy = 4;
gbc.gridheight = 3;
gbc.gridwidth = 1;
totalAmount.setHorizontalAlignment(JLabel.CENTER);
totalAmount.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
totalAmount.setFont(totalAmount.getFont().deriveFont(18.0f));
gridbag.setConstraints(totalAmount, gbc);
rp.add(totalAmount, gbc);
//row 5//////////////////////////////////////////////////////////////////
gbc.gridx = 2;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
dayHeading.setHorizontalAlignment(JLabel.CENTER);
dayHeading.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
dayHeading.setFont(dayHeading.getFont().deriveFont(18.0f));
gridbag.setConstraints(dayHeading, gbc);
rp.add(dayHeading, gbc);
gbc.gridx = 3;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
mon.setHorizontalAlignment(JLabel.CENTER);
mon.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
mon.setFont(mon.getFont().deriveFont(18.0f));
gridbag.setConstraints(mon, gbc);
rp.add(mon, gbc);
gbc.gridx = 4;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
tues.setHorizontalAlignment(JLabel.CENTER);
tues.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
tues.setFont(tues.getFont().deriveFont(18.0f));
gridbag.setConstraints(tues, gbc);
rp.add(tues, gbc);
gbc.gridx = 5;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
wed.setHorizontalAlignment(JLabel.CENTER);
wed.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
wed.setFont(wed.getFont().deriveFont(18.0f));
gridbag.setConstraints(wed, gbc);
rp.add(wed, gbc);
gbc.gridx = 6;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
thur.setHorizontalAlignment(JLabel.CENTER);
thur.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
thur.setFont(thur.getFont().deriveFont(18.0f));
gridbag.setConstraints(thur, gbc);
rp.add(thur, gbc);
gbc.gridx = 7;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
fri.setHorizontalAlignment(JLabel.CENTER);
fri.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
fri.setFont(fri.getFont().deriveFont(18.0f));
gridbag.setConstraints(fri, gbc);
rp.add(fri, gbc);
gbc.gridx = 8;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
sat.setHorizontalAlignment(JLabel.CENTER);
sat.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
sat.setFont(sat.getFont().deriveFont(18.0f));
gridbag.setConstraints(sat, gbc);
rp.add(sat, gbc);
gbc.gridx = 9;
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.gridwidth = 1;
sun.setHorizontalAlignment(JLabel.CENTER);
sun.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
sun.setFont(sun.getFont().deriveFont(18.0f));
gridbag.setConstraints(sun, gbc);
rp.add(sun, gbc);
//row 6//////////////////////////////////////////////////////////////
gbc.gridx = 2;
gbc.gridy = 6;
gbc.gridheight = 1;
gbc.gridwidth = 1;
dateHeading.setHorizontalAlignment(JLabel.CENTER);
dateHeading.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
dateHeading.setFont(dateHeading.getFont().deriveFont(18.0f));
gridbag.setConstraints(dateHeading, gbc);
rp.add(dateHeading, gbc);
int dateSpaceIndex = 3;
boolean flip = true;
for (int k = 0; k <= 6; k++)//create gridlines for day area
{
gbc.gridx = dateSpaceIndex;
gbc.gridy = 6;
gbc.gridheight = 1;
gbc.gridwidth = 1;
if(flip) dateSpace[k].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
else dateSpace[k].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
gridbag.setConstraints(dateSpace[k], gbc);
rp.add(dateSpace[k], gbc);
dateSpaceIndex++;
flip = !flip;
}
//row 7/////////////////////////////////////////////////////////////
gbc.gridx = 1;
gbc.gridy = 7;
gbc.gridheight = 3;
gbc.gridwidth = 1;
supt.setHorizontalAlignment(JLabel.CENTER);
supt.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
supt.setFont(supt.getFont().deriveFont(18.0f));
gridbag.setConstraints(supt, gbc);
rp.add(supt, gbc);
//row 10///////////////////////////////////////////////////////////
gbc.gridx = 1;
gbc.gridy = 10;
gbc.gridheight = 3;
gbc.gridwidth = 1;
foreman.setHorizontalAlignment(JLabel.CENTER);
foreman.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
foreman.setFont(foreman.getFont().deriveFont(18.0f));
gridbag.setConstraints(foreman, gbc);
rp.add(foreman, gbc);
//row 13-36 plus 7-12 time worked labels//////////////////////////
for (int r = 0; r <= 7; r++)
{
gbc.gridx = 1;
gbc.gridy = 13 + (3*r);
gbc.gridheight = 3;
gbc.gridwidth = 1;
mechanic[r].setHorizontalAlignment(JLabel.CENTER);
mechanic[r].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
mechanic[r].setFont(mechanic[r].getFont().deriveFont(18.0f));
gridbag.setConstraints(mechanic[r], gbc);
rp.add(mechanic[r], gbc);
}
for (int c = 0; c <= 9; c++){
gbc.gridx = 2;
gbc.gridy = 7 + (3*c);
gbc.gridheight = 1;
gbc.gridwidth = 1;
ot2[c].setHorizontalAlignment(JLabel.CENTER);
ot2[c].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
ot2[c].setFont(ot2[c].getFont().deriveFont(18.0f));
gridbag.setConstraints(ot2[c], gbc);
rp.add(ot2[c], gbc);
gbc.gridx = 2;
gbc.gridy = 8 + (3*c);
gbc.gridheight = 1;
gbc.gridwidth = 1;
ot1[c].setHorizontalAlignment(JLabel.CENTER);
ot1[c].setOpaque(true);
ot1[c].setBackground(shade);
ot1[c].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
ot1[c].setFont(ot1[c].getFont().deriveFont(18.0f));
gridbag.setConstraints(ot1[c], gbc);
rp.add(ot1[c], gbc);
gbc.gridx = 2;
gbc.gridy = 9 + (3*c);
gbc.gridheight = 1;
gbc.gridwidth = 1;
st[c].setHorizontalAlignment(JLabel.CENTER);
st[c].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
st[c].setFont(st[c].getFont().deriveFont(18.0f));
gridbag.setConstraints(st[c], gbc);
rp.add(st[c], gbc);
}
//row 37/////////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 37;
gbc.gridheight = 1;
gbc.gridwidth = 1;
locAndDescriptionLabel.setFont(locAndDescriptionLabel.getFont().deriveFont(18.0f));
gridbag.setConstraints(locAndDescriptionLabel, gbc);
rp.add(locAndDescriptionLabel);
gbc.gridx = 11;
gbc.gridy = 37;
gbc.gridheight = 1;
gbc.gridwidth = 1;
grandTotal.setHorizontalAlignment(JLabel.CENTER);
grandTotal.setOpaque(true);
grandTotal.setBackground(Color.BLACK);
grandTotal.setForeground(Color.WHITE);
grandTotal.setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
grandTotal.setFont(grandTotal.getFont().deriveFont(18.0f));
gridbag.setConstraints(grandTotal, gbc);
rp.add(grandTotal);
gbc.gridx = 12;
gbc.gridy = 37;
gbc.gridwidth = 1;
gbc.gridheight = 1;
grandTotalSpace.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
gridbag.setConstraints(grandTotalSpace, gbc);
rp.add(grandTotalSpace);
//row 38////////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 38;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.ipady = 80;
locAndDescSpace.setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
gridbag.setConstraints(locAndDescSpace, gbc);
rp.add(locAndDescSpace);
//row 39////////////////////////////////////////////////////////////////
gbc.ipady = 0; //reset to default
gbc.gridx = 0;
gbc.gridy = 39;
gbc.gridheight = 1;
gbc.gridwidth = 2;
toCertify.setFont(toCertify.getFont().deriveFont(18.0f));
gridbag.setConstraints(toCertify, gbc);
rp.add(toCertify);
//row 40///////////////////////////////////////////////////////////////
gbc.gridx = 0;
gbc.gridy = 40;
gbc.gridheight = 1;
gbc.gridwidth = 3;
authorizedBy.setFont(authorizedBy.getFont().deriveFont(18.0f));
gridbag.setConstraints(authorizedBy, gbc);
rp.add(authorizedBy);
for (int r = 0; r <= 9; r++)//gridlines for personnel space
{
gbc.gridx = 0;
gbc.gridy = 7 + (3*r);
gbc.gridheight = 3;
gbc.gridwidth = 1;
personnelSpace[r].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
gridbag.setConstraints(personnelSpace[r], gbc);
rp.add(personnelSpace[r]);
}
//create calendar grid lines
int yPointer = 7;
int xPointer = 3;
int shadePtr = 8;
for (int j = 0; j <= 299; j++)
{
gbc.gridx = xPointer;
gbc.gridy = yPointer;
gbc.gridheight = 1;
gbc.gridwidth = 1;
calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));
if (yPointer == shadePtr){ //if row number = shadePtr then color the cell
calendarGridLines[j].setOpaque(true);
calendarGridLines[j].setBackground(shade);
}
gridbag.setConstraints(calendarGridLines[j], gbc);
rp.add(calendarGridLines[j]);
xPointer++; //go to next cell in row
j++; //use the next jlabel
gbc.gridx = xPointer;
gbc.gridy = yPointer;
gbc.gridheight = 1;
gbc.gridwidth = 1;
calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.BLACK));
if (yPointer == shadePtr){ //if row number = shadePtr then color the cell
calendarGridLines[j].setOpaque(true);
calendarGridLines[j].setBackground(shade);
}
gridbag.setConstraints(calendarGridLines[j], gbc);
rp.add(calendarGridLines[j]);
xPointer++; //go to next cell in row
if(xPointer == 13) //if end of column then go to next row and reset column pointer to 3 and increment shade pointer by 3
{
yPointer++; //go down a row
xPointer = 3;
if((j % 3) == 0) {
shadePtr = yPointer;
}
}
}
JButton printTest = new JButton("PrintTest");
printTest.addActionListener(this);
gbc.gridx = 0;
gbc.gridy = 41;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gridbag.setConstraints(printTest, gbc);
rp.add(printTest);
}
#Override
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog()){
try{
printJob.print();
}
catch(Exception ex){
throw new RuntimeException(ex);
}
}
}
#Override
public int print(Graphics g, PageFormat pf, int index)
throws PrinterException {
Graphics2D g2 = (Graphics2D)g;
if (index >= 1){
return Printable.NO_SUCH_PAGE;
}
else {
AffineTransform originalTransform = g2.getTransform();
double scaleX = pf.getImageableWidth() / rp.getWidth();
double scaleY = pf.getImageableHeight() / rp.getHeight();
// Maintain aspect ratio
double scale = Math.min(scaleX, scaleY);
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.scale(scale, scale);
rp.printAll(g2);
g2.setTransform(originalTransform);
return Printable.PAGE_EXISTS;
}
}
}
I put my main GUI panel inside another JPanel, which sits inside the JScrollPane. This prevents my main GUI from resizing to the frame size; instead the "outer" JPanel is what gets resized.
On your JPanel you can use both :
setSize( w, h)
setPreferredSize()
Or maybe add a component listener to handle manually the "repaint / invalidate" on resize events
JPanel component = new JPanel();
component.addComponentListener(new ComponentListener()
{
public void componentResized(ComponentEvent evt) {
Component c = (Component)evt.getSource();
//........
}
});
I have JPanel inside vertical JSplitPane. JPanel contains jlabels and jtextfields. When I shrink height of JPanel by moving JSplitPane's divider All components in jpanel are resized themselves. How to tell them not to resize when height of parent jpanel shrinks.
I cannot size minSize for JPanel because it makes impossible for JSplitPane to move divider.
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setDividerSize(10);
splitPane.setOneTouchExpandable(true);
JPanel searchPanel = createSearchPanel();
splitPane.setDividerLocation(searchPanel.getPreferredSize().height + 5);
splitPane.setTopComponent(searchPanel);
As you see there is searchPanel. Let's see it:
JPanel searchPanel = new JPanel(new GridBagLayout()) {
Dimension minSize = new Dimension(200, 0);
#Override
public Dimension getMinimumSize() {
return minSize;
}
};
searchPanel.setBorder(BorderFactory.createTitledBorder("Search query"));
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0, 0,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL,
new Insets(5, 2, 5, 3), 0, 0);
searchPanel.add(eventLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 3;
searchPanel.add(eventLabelField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
searchPanel.add(timestampLabel, gbc);
gbc.gridx = 1;
searchPanel.add(timestampStartField, gbc);
gbc.gridx = 2;
searchPanel.add(timestammpToLabel, gbc);
gbc.gridx = 3;
searchPanel.add(timestampEndField, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
searchPanel.add(locationLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 3;
searchPanel.add(locationField, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
searchPanel.add(durationMagnitudeLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 3;
searchPanel.add(durationMagnitudeMinField, gbc);
gbc.gridx = 2;
searchPanel.add(durationToLabel, gbc);
gbc.gridx = 3;
searchPanel.add(durationMagnitudeMaxField, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.PAGE_END;
gbc.weighty = 1.0;
gbc.ipadx = 2;
gbc.ipady = 2;
gbc.insets = new Insets(15, 0, 0, 0);
searchPanel.add(searchButton, gbc);
When I move up vertical divider the height of searchPanel shrinks and components look like:
You see that jtextFields got much smaller than they were after I moved divider up
Please, help me here.
I have changed your code. Use weightx property of GridBagConstraint with GridBagConstraints.HORIZONTAL fill, it helps components to fill their cell properly.
Example code:
JPanel searchPanel = new JPanel(new GridBagLayout()) {
Dimension minSize = new Dimension(200, 0);
#Override
public Dimension getMinimumSize() {
return minSize;
}
};
searchPanel.setBorder(BorderFactory.createTitledBorder("Search query"));
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0, 0,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL,
new Insets(5, 2, 5, 3), 0, 0);
searchPanel.add(new JLabel("1"), gbc);
gbc.gridx = 1;
gbc.gridwidth = 3;
gbc.weightx = 1;
searchPanel.add(new JTextField(), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
searchPanel.add(new JLabel("1"), gbc);
gbc.gridx = 1;
gbc.weightx = 1;
searchPanel.add(new JTextField(), gbc);
gbc.gridx = 2;
gbc.weightx = 0;
searchPanel.add(new JLabel("1"), gbc);
gbc.gridx = 3;
gbc.weightx = 1;
searchPanel.add(new JTextField(), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 0;
searchPanel.add(new JLabel("1"), gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 3;
gbc.weightx = 1;
searchPanel.add(new JTextField(), gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.weightx = 0;
searchPanel.add(new JLabel("1"), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.weightx = 1;
searchPanel.add(new JTextField(), gbc);
gbc.gridx = 2;
gbc.weightx = 0;
searchPanel.add(new JLabel("1"), gbc);
gbc.gridx = 3;
gbc.weightx = 1;
searchPanel.add(new JTextField(), gbc);
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.PAGE_END;
gbc.weighty = 1.0;
gbc.ipadx = 2;
gbc.ipady = 2;
gbc.insets = new Insets(15, 0, 0, 0);
gbc.weightx = 0;
searchPanel.add(new JButton("b"), gbc);
return searchPanel;
Watch docs How to use GridBagLayout
Results:
Edit: Sorry, I'm using awful names for labels)
Add a dummy JPanel to the bottom and set weightY=1 for the JPanel. ALl the rest component should have weightY=0. Thus on height increasing all the additional pixels are targeted to the dummy JPanel.
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();
}
});
}
}