JFrame Layout management - java

With the following code I tried to create a layout for a calculator frame.
The output I get seems as if there is something going extremely wrong but I can't spot it.
Output:
My question is can you try to compile this and see if you get the same output as me?
If you do is there anything I should be checking when getting this sort of problem. Thanks
Code:
package mycalculator;
import javax.swing.*;
import java.awt.*;
public class MyCalculatorGUI extends JFrame {
//initialise all the components
JPanel mainPanel = new JPanel();
JPanel memPanel = new JPanel();
JPanel advFuncPanel = new JPanel();
JPanel wordFuncPanel = new JPanel();
JPanel numPanel = new JPanel();
JPanel basicFuncPanel = new JPanel();
JTextField txtDisplay = new JTextField(100);
JToggleButton mPlus = new JToggleButton("M+");
JButton mClear = new JButton("CM");
JButton mA = new JButton("A");
JButton mB = new JButton("B");
JButton mC = new JButton("C");
JButton mD = new JButton("D");
JButton aSq = new JButton("x"+ "\u00B2");
JButton aCu = new JButton("x" + "\u00B3");
JButton aPowa = new JButton("x" + "\u00AA");
JButton aInv = new JButton("x" + "\u00AF" + "\u00B9");
JButton aSqrt = new JButton("\u221A" + "x");
JButton aFact = new JButton("x!");
JButton btnSin = new JButton("sin(x)");
JButton btnCos = new JButton("cos(x)");
JButton btnTan = new JButton("tan(x)");
JButton btnaSin = new JButton("arcsin(x)");
JButton btnaCos = new JButton("arccos(x)");
JButton btnaTan = new JButton("arctan(x)");
JToggleButton hyp = new JToggleButton("hyp");
JButton btnAbs = new JButton("abs(x)");
JButton btnExp = new JButton("exp(x)");
JButton btnLog = new JButton("log(x)");
JButton btnLn = new JButton("ln(x)");
JButton btnLoga = new JButton("loga(x)");
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
JButton btn0 = new JButton("0");
JButton btnDot = new JButton(".");
JButton btnCl = new JButton("Cl");
JButton btnBs = new JButton("\u00AB");
JButton btnPlus = new JButton("+");
JButton btnMinus = new JButton("-");
JButton btnMult = new JButton("*");
JButton btnDiv = new JButton("\u00F7");
JButton btnEq = new JButton("=");
public static void main(String[] args) {
new MyCalculatorGUI();
}
public MyCalculatorGUI() {
// create the frame for the Calculator
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle("Calculator");
// parent panel containes every other panel
mainPanel.setLayout(new GridBagLayout());
this.add(mainPanel);
// text display
txtDisplay.setEditable(false);
addComp(mainPanel, txtDisplay, 0, 0, 4, 1);
// --------------------------------------------------------------------------
// memory panel, flow layout, 6 buttons same size, spans gridwidth 2
memPanel.setLayout(new FlowLayout());
// add button to panel
memPanel.add(mPlus);
memPanel.add(mClear);
memPanel.add(mA);
memPanel.add(mB);
memPanel.add(mC);
memPanel.add(mD);
// add panel to main panel
addComp(mainPanel, memPanel, 0, 1, 2, 1);
// --------------------------------------------------------------------------
// advFuncPanel, flow layout, 6 buttons same size, spans gridwidth 2
advFuncPanel.setLayout(new FlowLayout());
// add button to panel
advFuncPanel.add(aSq);
advFuncPanel.add(aCu);
advFuncPanel.add(aPowa);
advFuncPanel.add(aInv);
advFuncPanel.add(aSqrt);
advFuncPanel.add(aFact);
// add panel to main panel
addComp(mainPanel, advFuncPanel, 0, 2, 2, 1);
// --------------------------------------------------------------------------
// wordFuncPanel, grid layout (3 rows, 4 columns), 12 buttons same size, spans gridwidth 2
wordFuncPanel.setLayout(new GridLayout(3, 4));
// add buttons to panel
wordFuncPanel.add(btnSin);
wordFuncPanel.add(btnaSin);
wordFuncPanel.add(hyp);
wordFuncPanel.add(btnLog);
wordFuncPanel.add(btnCos);
wordFuncPanel.add(btnaCos);
wordFuncPanel.add(btnAbs);
wordFuncPanel.add(btnLn);
wordFuncPanel.add(btnTan);
wordFuncPanel.add(btnaTan);
wordFuncPanel.add(btnExp);
wordFuncPanel.add(btnLoga);
// add panel to main panel
addComp(mainPanel, wordFuncPanel, 0, 3, 2, 1);
// --------------------------------------------------------------------------
// numPanel, gridbaglayout, spans gridheight 3
numPanel.setLayout(new GridBagLayout());
// add buttons to panel
addComp(numPanel, btn1, 0, 0, 1, 1);
addComp(numPanel, btn2, 1, 0, 1, 1);
addComp(numPanel, btn3, 2, 0, 1, 1);
addComp(numPanel, btn4, 0, 1, 1, 1);
addComp(numPanel, btn5, 1, 1, 1, 1);
addComp(numPanel, btn6, 2, 1, 1, 1);
addComp(numPanel, btn7, 0, 2, 1, 1);
addComp(numPanel, btn8, 1, 2, 1, 1);
addComp(numPanel, btn9, 2, 2, 1, 1);
addComp(numPanel, btn0, 0, 3, 2, 1);
addComp(numPanel, btnDot, 2, 3, 1, 1);
addComp(numPanel, btnCl, 0, 4, 2, 1);
addComp(numPanel, btnBs, 2, 4, 1, 1);
// add panel to mainpanel
addComp(mainPanel, numPanel, 2, 1, 1, 3);
// --------------------------------------------------------------------------
//basicFuncPanel, verticalboxlayout, spans gridheight 3
basicFuncPanel.setLayout(new BoxLayout(basicFuncPanel, BoxLayout.Y_AXIS));
// add buttons to panel
basicFuncPanel.add(btnPlus);
basicFuncPanel.add(btnMinus);
basicFuncPanel.add(btnMult);
basicFuncPanel.add(btnDiv);
basicFuncPanel.add(btnEq);
// add panel to main panel
addComp(mainPanel, basicFuncPanel, 3, 1, 1, 3);
// --------------------------------------------------------------------------
this.pack();
this.setVisible(true);
}
private void addComp(JPanel panel, JComponent comp, int xPos, int yPos, int compWidth, int compHeight) {
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = xPos;
gridConstraints.gridy = yPos;
gridConstraints.gridwidth = compWidth;
gridConstraints.gridheight = compHeight;
gridConstraints.weightx = 100;
gridConstraints.weighty = 100;
gridConstraints.insets = new Insets(5, 5, 5, 5);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.fill = GridBagConstraints.BOTH;
panel.add(comp, gridConstraints);
}
private JComponent[] components = { mPlus, mClear, mA, mB, mC, mD, aSq, aCu, aPowa, aInv, aSqrt, aFact,
btnSin, btnCos, btnTan, btnaSin, btnaCos, btnaTan, hyp, btnAbs, btnExp, btnLog, btnLn, btnLoga,
btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnDot, btnCl, btnBs, btnPlus, btnMinus,
btnMult, btnDiv, btnEq };
public JComponent[] getComponents() {
return components;
}
}

Just do one change and everything will work fine.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyCalculatorGUI();
}
});
}
Use SwingUtilities.invokeLater() to make sure that EDT is initialized properly.
Read more
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
EDIT
Some time this.setResizable(false); create issues while re-sizing or packing the components in the JFrame.

Related

How to fix error in GridLayout/GridBagConstraints?

Why GridLayot not working in Swing Java?
I need to place element at concrete cell, but they placing wrong (picture)
How to place elements to concrete cell in Java Swing with grid layout?
My code:
package com.KvaksManYT;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3, 2, 2, 2));
container.add(but1, onPosition(1, 2));
container.add(but2, onPosition(2, 2));
container.add(but3, onPosition(1, 1));
container.add(but4, onPosition(2, 1));
}
private JButton but1 = new JButton("Press 1");
private JButton but2 = new JButton("Press 2");
private JButton but3 = new JButton("Press 3");
private JButton but4 = new JButton("Press 4");
private GridBagConstraints onPosition(int x, int y) {
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.BOTH;
layConstraints.gridx = x;
layConstraints.gridy = y;
return layConstraints;
}
}
The GridBagConstraints is used for Grid Bag Layout, rather than Grid Layout.
You have to start counting at 0 too:
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.NONE;
layConstraints.insets = new Insets(3, 2, 2, 2);
Container container = this.getContentPane();
container.setLayout(new GridBagLayout());
container.add(but1, onPosition(0, 1, layConstraints));
container.add(but2, onPosition(1, 1, layConstraints));
container.add(but3, onPosition(0, 0, layConstraints));
container.add(but4, onPosition(1, 0, layConstraints));
}

Difficulty aligning componenents within multiple JPanels

I am trying to create a layout where I have two panels with borders around them. I would like the rectangular borders to be of equal size. I would also like the JTextField in the bottom panel to be of that smaller width.
The problem is that, whenever I fill the bottom panel horizontally (using GridBagConstraints.HORIZONTAL), the checkbox and label inside that panel become misaligned with the checkbox and label in the panel above it.
I was hoping an experienced developer could offer insight into how I could make the two JPanels and their rectangular borders equal in size with one another, while also having their checkboxes and labels aligned.
Here is what it looks like now:
Here is code to reproduce the problem:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class Example
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
MyFrame frame = new MyFrame();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
class MyFrame
{
private JFrame frame;
private MyDialog dialog;
public MyFrame()
{
frame = new JFrame();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
dialog = new MyDialog(frame);
}
}
class MyDialog
{
private JDialog dialog;
private JPanel mainPanel,
panel1,
inputPanel1,
panel2,
inputPanel2;
private JLabel titleLabel,
label1,
label2;
private JCheckBox checkBox1,
checkBox2;
private JTextField textField1,
textField2;
public MyDialog(JFrame frame)
{
dialog = new JDialog(frame, true);
buildPanel();
dialog.add(mainPanel);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
private void buildPanel()
{
mainPanel = new JPanel(new GridBagLayout());
titleLabel = new JLabel("Title");
checkBox1 = new JCheckBox("checkBox1");
label1 = new JLabel("label1:");
textField1 = new JTextField(15);
inputPanel1 = new JPanel(new GridBagLayout());
inputPanel1.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel1.add(label1, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
inputPanel1.add(textField1, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel1 = new JPanel(new GridBagLayout());
Border border1 = BorderFactory.createEtchedBorder();
panel1.setBorder(border1);
panel1.add(checkBox1, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel1.add(inputPanel1, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
checkBox2 = new JCheckBox("checkBox2");
label2 = new JLabel("label2:");
textField2 = new JTextField(8);
inputPanel2 = new JPanel(new GridBagLayout());
inputPanel2.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel2.add(label2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
inputPanel2.add(textField2, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2 = new JPanel(new GridBagLayout());
Border border2 = BorderFactory.createEtchedBorder();
panel2.setBorder(border2);
panel2.add(checkBox2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2.add(inputPanel2, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(titleLabel, getConstraints(0, 0, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE));
mainPanel.add(panel1, getConstraints(0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
// When I fill panel2 horizontally, the checkbox becomes misaligned with the above checkbox:
//mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
}
private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor, int fill)
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.anchor = anchor;
gbc.fill = fill;
return gbc;
}
}
What I did was
Make your inputPanelX have FlowLayout with FlowLayout.LEADING instead of using GirdBagLayout for them.
inputPanel1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
And the scond one I just made the same Dimension as the first one
inputPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING)){
Dimension dim = new Dimension(inputPanel1.getPreferredSize());
public Dimension getPreferredSize(){
return new Dimension(dim);
}
};
That's all I changed. See full code below
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class Example
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
MyFrame frame = new MyFrame();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
class MyFrame
{
private JFrame frame;
private MyDialog dialog;
public MyFrame()
{
frame = new JFrame();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
dialog = new MyDialog(frame);
}
}
class MyDialog
{
private JDialog dialog;
private JPanel mainPanel,
panel1,
inputPanel1,
panel2,
inputPanel2;
private JLabel titleLabel,
label1,
label2;
private JCheckBox checkBox1,
checkBox2;
private JTextField textField1,
textField2;
public MyDialog(JFrame frame)
{
dialog = new JDialog(frame, true);
buildPanel();
dialog.add(mainPanel);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
private void buildPanel()
{
mainPanel = new JPanel(new GridBagLayout());
titleLabel = new JLabel("Title");
checkBox1 = new JCheckBox("checkBox1");
label1 = new JLabel("label1:");
textField1 = new JTextField(15);
inputPanel1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
inputPanel1.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel1.add(label1);
inputPanel1.add(textField1);
panel1 = new JPanel(new GridBagLayout());
Border border1 = BorderFactory.createEtchedBorder();
panel1.setBorder(border1);
panel1.add(checkBox1, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel1.add(inputPanel1, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
checkBox2 = new JCheckBox("checkBox2");
label2 = new JLabel("label2:");
textField2 = new JTextField(8);
inputPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING)){
Dimension dim = new Dimension(inputPanel1.getPreferredSize());
public Dimension getPreferredSize(){
return new Dimension(dim);
}
};
inputPanel2.setBorder(BorderFactory.createEmptyBorder(0, 17, 0, 0)); // indent the label and textfield
inputPanel2.add(label2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
inputPanel2.add(textField2, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2 = new JPanel(new GridBagLayout());
Border border2 = BorderFactory.createEtchedBorder();
panel2.setBorder(border2);
panel2.add(checkBox2, getConstraints(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
panel2.add(inputPanel2, getConstraints(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(titleLabel, getConstraints(0, 0, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE));
mainPanel.add(panel1, getConstraints(0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE));
// When I fill panel2 horizontally, the checkbox becomes misaligned with the above checkbox:
//mainPanel.add(panel2, getConstraints(0, 2, 2, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
}
private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor, int fill)
{
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.anchor = anchor;
gbc.fill = fill;
return gbc;
}
}

JButton not initialized in a method

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener{
JButton[] nums;
JButton eq, mult, div, clr, clrEnt, sub, add, dot;
JTextArea txtArea = new JTextArea();
public Calculator() {
super("Calculator");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(6, 1, 0, 5));
add(pane);
JPanel paneSecond = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneThird = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneFourth = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneFifth = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneSixth = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneSeventh = new JPanel(new GridLayout(1, 3, 5, 5));
nums = new JButton[11];
//add = new JButton();
addOpButton(eq, "=");
addOpButton(mult, "x");
addOpButton(div, "/");
addOpButton(clr, "C");
addOpButton(clrEnt, "CE");
addOpButton(sub, "-");
addOpButton(add, "+");
addOpButton(dot, ".");
for (int i = 0; i < nums.length; i++) {
nums[i] = new JButton("" + i);
nums[i].setActionCommand(nums[i].toString());
nums[i].addActionListener(this);
}
addPanel(paneSecond, 1, 4);
addPanel(paneThird, 4, 7);
addPanel(paneFourth, 7, 10);
//addButtons(paneFifth, add, nums[0], sub);
pane.add(paneSecond);
pane.add(paneThird);
pane.add(paneFourth);
pane.add(paneFifth);
pane.add(paneSixth);
pane.add(paneSeventh);
pack();
}
void addPanel(JComponent pane, int start, int condition) {
for (int i = start; i < condition; i++) {
pane.add(nums[i]);
}
}
void addButtons(JComponent pane, JButton btn1, JButton btn2, JButton btn3) {
pane.add(btn1);
pane.add(btn2);
pane.add(btn3);
}
void addOpButton(JButton btn, String op) {
btn = new JButton(op);
btn.setActionCommand(op);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
Calculator calc = new Calculator();
}
}
In the addOpButton method none of my buttons are being initialized. I am not sure why though. The string is being passed and used but not the button. Even after initializing one of the buttons (the "add" button in the constructor with the removal of the comment) the button is still null in the method. I cannot figure out why. Any help is appreciated.
Java is "pass by value". That means that if you try to pass a reference, the reference is copied and then passed.
In practices this means that the btn parameter you give to addOpButton is a copy, and the other copy is held by whoever called the method. When you then do btn = new you're assigning something to the copy, giving it a command and an actionlistener, and then it's discarded. The caller still has a reference to his own copy.

Can't display enough JLabels/TextFields properly

I am trying to display roughly 7 or 8 multiple text fields and JLabels in a single frame. I am having trouble getting them all to show up. The only way I know to display the individual parts of the GUI is to create a JFrame, then create a container within that frame, then create multiple panels and add them to the container. Is there a better way to do this? One that isn't so restricting and allows me to display more than 4 frames? (I'm limited to only choosing NORTH, EAST, SOUTH, WEST and only one item will show up at those locations)
Here is my code:
Container content = n.getContentPane();
Container contentTwo = n.getContentPane();
JTextField JField = new JTextField(agentID);
JTextField stateField = new JTextField("Running");
JTextField transField = new JTextField(5);
JTextField opsField = new JTextField("0");
stateField.setEnabled(false);
transField.setEnabled(false);
JField.setEnabled(false);
opsField.setEnabled(false);
JLabel stateLabel = new JLabel("State:");
JLabel transLabel = new JLabel("Amount transferred:");
JLabel opsLabel = new JLabel("Operations Completed:");
JPanel fundsPanel = new JPanel(new BorderLayout());
JLabel agentLabel = new JLabel("Agent ID: ");
agentLabel.setDisplayedMnemonic(KeyEvent.VK_ENTER);
stateLabel.setLabelFor(stateField);
transLabel.setLabelFor(transField);
agentLabel.setLabelFor(JField);
opsLabel.setLabelFor(opsField);
fundsPanel.add(agentLabel, BorderLayout.WEST);
fundsPanel.add(JField, BorderLayout.CENTER);
content.add(fundsPanel, BorderLayout.NORTH);
JLabel accLabel = new JLabel("Amount in $: ");
JPanel accPanel = new JPanel(new BorderLayout());
JPanel accPanelTwo = new JPanel(new BorderLayout());
JPanel accPanelThree = new JPanel(new BorderLayout());
accLabel.setDisplayedMnemonic(KeyEvent.VK_ENTER);
JFormattedTextField accTextField = new JFormattedTextField(amount);
accTextField.setEnabled(false);
JLabel opLabel = new JLabel("Operations per second:");
opLabel.setDisplayedMnemonic(KeyEvent.VK_ENTER);
JTextField accTextFieldTwo = new JTextField(Double.toString(opsPerSec), 5);
accTextFieldTwo.setEnabled(false);
accLabel.setLabelFor(accTextField);
opLabel.setLabelFor(accTextFieldTwo);
accPanel.add(accLabel, BorderLayout.WEST);
accPanel.add(accTextField, BorderLayout.CENTER);
accPanelTwo.add(opLabel, BorderLayout.WEST);
accPanelTwo.add(accTextFieldTwo, BorderLayout.CENTER);
accPanelTwo.add(opsLabel, BorderLayout.EAST);
accPanelTwo.add(opsField, BorderLayout.NORTH);
accPanelThree.add(stateLabel, BorderLayout.WEST);
accPanelThree.add(stateField, BorderLayout.CENTER);
content.add(accPanel, BorderLayout.CENTER);
content.add(accPanelTwo, BorderLayout.EAST);
contentTwo.add(accPanelThree, BorderLayout.EAST);
JButton jButton1 = new JButton("Stop agent");
JButton jButton2 = new JButton("Dismiss");
jButton1.addActionListener(handler);
jButton2.addActionListener(handler);
buttonPanel.setLayout(new GridLayout(2, 3, 3, 3));
n.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(jButton2, null);
buttonPanel.add(jButton1, null);
n.pack();
I just coded the first few fields of your panel using the GridBagLayout to show you how to use the layout.
You'll have to finish the coding to get your full form created.
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GridBagPanel {
protected static final Insets leftInsets = new Insets(10, 10, 0, 0);
protected static final Insets rightInsets = new Insets(10, 10, 0, 10);
protected JPanel mainPanel;
protected String agentID;
public GridBagPanel() {
createPartControl();
}
private void createPartControl() {
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel stateLabel = new JLabel("State:");
addComponent(mainPanel, stateLabel, 0, gridy, 1, 1, leftInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField stateField = new JTextField("Running");
stateField.setEnabled(false);
stateLabel.setLabelFor(stateField);
addComponent(mainPanel, stateField, 1, gridy++, 1, 1, rightInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel transLabel = new JLabel("Amount transferred:");
addComponent(mainPanel, transLabel, 0, gridy, 1, 1, leftInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField transField = new JTextField(5);
transField.setEnabled(false);
transLabel.setLabelFor(transField);
addComponent(mainPanel, transField, 1, gridy++, 1, 1, rightInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel opsLabel = new JLabel("Operations Completed:");
addComponent(mainPanel, opsLabel, 0, gridy, 1, 1, leftInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField opsField = new JTextField("0");
opsField.setEnabled(false);
opsLabel.setLabelFor(opsField);
addComponent(mainPanel, opsField, 1, gridy++, 1, 1, rightInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel agentLabel = new JLabel("Agent ID: ");
addComponent(mainPanel, opsLabel, 0, gridy, 1, 1, leftInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField agentField = new JTextField(agentID);
agentField.setEnabled(false);
agentLabel.setLabelFor(agentField);
addComponent(mainPanel, agentField, 1, gridy++, 1, 1, rightInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
}
protected void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
}

Too much space between components in Spring layout

I want to create a JFrame by hand and use spring layout to do this. But, my finally output is not good. The space between my rows is so much, and between my radio buttons too:
My code:
public final class NewUserFrame1 extends JFrame {
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
JLabel fnamelbl = new JLabel("First name");
JLabel lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
JTextField fntf = new JTextField(10);
JTextField lntf = new JTextField(10);
JLabel gndlnl = new JLabel("Gender");
JRadioButton malerb = new JRadioButton("Male");
JRadioButton femalerb = new JRadioButton("Female");
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
JLabel registnm = new JLabel("Registration ID is:");
JLabel showreglbl = new JLabel();
JLabel regtemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
panel.add(malerb);
panel.add(femalerb);
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 4);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
}
Now:
Instead of calling setSize call pack on JFrame within your NewUserFrame1 constructor.
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
//setSize(800, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
pack();
}
Also change the parameters of SpringUtilities.makeCompactGrid method in following way:
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 4);//change yPad to 4 instead of 100. It sets the vertical height between two rows
Your code is not compilable (missing imports).
You wrote:
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 100);
The last argument is yPad. Change this to 10 (or lower value if you want), for example:
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 10);
But still - label will be to high etc., but it's a different issue. Keep playing with panel's size and your component's size.
In case of radio buttons - change
panel.add(malerb);
panel.add(femalerb);
To something like:
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radioPanel.add(malerb);
radioPanel.add(femalerb);
panel.add(radioPanel);
panel.add(new JLabel());
The last line is needed because you declared your layout to have 3 columns.

Categories

Resources