Java Swing UI Layout - java

I am creating a basic user interface in Swing and was hoping for some help. Below is a screenshot of what I am trying to achieve:
My code currently is as follows:
package testui;
import java.awt.Container;
import javax.swing.*;
public class TestUI{
private JTextField outputArea = new JTextField();
private JTextField errorReportArea = new JTextField();
private JPanel inputPanel = new JPanel();
private JLabel nameLabel = new JLabel("Item Name");
private JLabel numberLabel = new JLabel("Number of units (or Volume in L)");
private JLabel priceLabel = new JLabel("Price per unit (Or L) in pence");
private JTextField nameField = new JTextField(10);
private JTextField numberField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JButton addVolumeButton = new JButton("Add by Volume");
private JButton addNumberButton = new JButton("Add by number of units");
public TestUI() {
JFrame frame = new JFrame("Fuel Station");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outputArea.setEditable(false);
errorReportArea.setEditable(false);
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
inputPanel.add(nameLabel);
inputPanel.add(nameField);
inputPanel.add(numberLabel);
inputPanel.add(numberField);
inputPanel.add(priceLabel);
inputPanel.add(priceField);
inputPanel.add(addVolumeButton);
inputPanel.add(addNumberButton);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(outputArea);
contentPane.add(errorReportArea);
contentPane.add(inputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
TestUI test1 = new TestUI();
}
}
Which looks like this:
So what I would like to do is set a specific size for the top two JTextFields, as the top one will contain multiple lines of text, and the one below will contain just one line of text. I am unsure how to do this without using setSize, as I have been told it is bad coding practice to use this.
I would also like to add some padding between the JLabels, JTextFields and JButtons in the bottom JPanel.
If anyone could give me some suggestions on resizing these components I would be most grateful

Since you want your textfields to be multilined, use JTextAreas. JTextFields are single lined only.
Your components are right next to each other which isn't the same look as your intended outcome. There may be some method that gives your components some breathing room before you would call frame.pack()
Look for any method that can make a component fill the total amount of room it's given; especially when you want something to fill a large chunk of space.
You can set the number of columns instead of using setSize() for your JTextFields/JTextAreas. Just saying.
Reviewing all of Java's Layout Managers would help you get a grasp of the capabilities and use cases for each layout manager

There are a few layout managers that are flexible enough to perform this, such as Mig, Gridbag, and SpringLayout.
In your case, you'd have the following constraints:
outputarea - south border constrained to be ###px from the north border of the contentPane
errorReportArea - north border constrained to be 0px from outputarea's south, and south border constrained to be 0px from inputPanel's north.
inputPanel - north border constrained to be ##px from the south border of the contentPane.
GUI builders such as WindowBuilder will allow you to do this pretty quickly. You just drop in the layout onto the contentPane and then set the constraints.

If you have to use a box layout look at the glue and rigidArea methods in Box. If you can use other layouts, go with those suggested by the other answers.

I have created a solution with the MigLayout manager.
Here are some recommendations:
Put application code outside the constructor; in the solution, the code
is placed in the initUI() method.
The application should be started on EDT by calling the
EventQueue.invokeLater(). (See the main() method of the provided solution.)
Use a modern, flexible layout manager: MigLayout, GroupLayout, or FormLayout.
Take some time to study them to fully understand the layout management process. It
is important have a good understanding of this topic.
Shorten the labels; use more descriptive tooltips
instead.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutSolution extends JFrame {
private JTextArea outputArea;
private JTextField errorReportField;
private JLabel nameLabel;
private JLabel numberLabel;
private JLabel priceLabel;
private JTextField nameField;
private JTextField numberField;
private JTextField priceField;
private JButton addVolumeButton;
private JButton addNumberButton;
public MigLayoutSolution() {
initUI();
}
private void initUI() {
setLayout(new MigLayout());
outputArea = new JTextArea(10, 20);
errorReportField = new JTextField(15);
nameLabel = new JLabel("Item name");
numberLabel = new JLabel("# of units");
numberLabel.setToolTipText("Number of units (or Volume in L)");
priceLabel = new JLabel("Price per unit");
priceLabel.setToolTipText("Price per unit (Or L) in pence");
nameField = new JTextField(10);
numberField = new JTextField(10);
priceField = new JTextField(10);
addVolumeButton = new JButton("AddVol");
addVolumeButton.setToolTipText("Add by Volume");
addNumberButton = new JButton("AddNum");
addNumberButton.setToolTipText("Add by number of units");
add(new JScrollPane(outputArea), "grow, push, wrap");
add(errorReportField, "growx, wrap");
add(nameLabel, "split");
add(nameField);
add(numberLabel);
add(numberField);
add(priceLabel);
add(priceField);
add(addVolumeButton);
add(addNumberButton);
pack();
setTitle("Fuel station");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutSolution ex = new MigLayoutSolution();
ex.setVisible(true);
}
});
}
}

Related

Using FlowLayout manager to keep 3 panels in distinct rows

I used a GridLayout mananger to create my gui, but I don't like the extra space that makes my buttons look tiny.
My GUI
I want it to look more like this one.
Good GUI
I have tried placing the first two rows in another gridlayout and putting it all together in a flow layout, but it did not work. They just end up being side by side, unless the window gets really small, as it should since it is a flowlayout. Any Ideas?
Standard Services Panel constructor
public StandardServices()
{
// Create GridLayout manager with 5 rows and 1 column
setLayout(new GridLayout(5,1));
// Create the check boxes.
iHardDrive = new JCheckBox("Install Hard Drive ($25.00)");
ram = new JCheckBox("Install Ram ($15.00)");
virus = new JCheckBox("Remove Virus ($50.00)");
fHardDrive = new JCheckBox("Format Hard Drive ($80.00)");
labourQuote = new JCheckBox("Hourly Labour Qoute ($10.00)");
//Add a border around the panel.
setBorder(BorderFactory.createTitledBorder("Standard Services"));
// Add the checkboxes to the panel.
add(iHardDrive);
add(ram);
add(virus);
add(fHardDrive);
add(labourQuote);
}
Hourly Services Panel constructor
public HourlyService()
{
// Created grid layout with 2 rows, 1 column
setLayout(new GridLayout(2,1));
// Create labels to display instructions.
cost = new JLabel("Parts Cost:");
labour = new JLabel("Hours of Labour:");
// Create two text fields 10 characters wide.
costTextField = new JTextField(10);
labourTextField = new JTextField(10);
// Place a 0 in the text fields.
costTextField.setText("0");
labourTextField.setText("0");
// Add a border around the layout
setBorder(BorderFactory.createTitledBorder("Hourly Service"));
// Add labels and text fields to the panel.
add(cost);
add(costTextField);
add(labour);
add(labourTextField);
}
LU Store GUI constructor
public MyStoreGui()
{
//Display a title
setTitle("LU Computer Store");
//Specify a default action for the close button
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set the size of the window
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Create a GridLayout manager
setLayout(new GridLayout(3,1));
//setLayout(new FlowLayout());
// create custom panels
standard = new StandardServices();
hourly = new HourlyService();
//Create the button panel
buildButtonPanel();
add(standard);
add(hourly);
add(buttonPanel);
// Display the window
setVisible(true);
}
Instead of using a GridLayout which will give equal spacing to all the components based on the largest component, use a GridBagLayout which will not only provide you with more control, but which will honour the preferred size of the individual components
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MyStoreGui());
frame.pack();
frame.setVisible(true);
}
});
}
public final class MyStoreGui extends JPanel {
public MyStoreGui() {
setLayout(new GridBagLayout());
//setLayout(new FlowLayout());
// create custom panels
StandardServices standard = new StandardServices();
HourlyService hourly = new HourlyService();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
//Create the button panel
JPanel buttonPanel = buildButtonPanel();
add(standard, gbc);
add(hourly, gbc);
add(buttonPanel, gbc);
// Display the window
setVisible(true);
}
protected JPanel buildButtonPanel() {
JPanel panel = new JPanel();
panel.add(new JButton("Calclate Changes"));
panel.add(new JButton("Exit"));
return panel;
}
}
public class StandardServices extends JPanel {
public StandardServices() {
// Create GridLayout manager with 5 rows and 1 column
setLayout(new GridLayout(5, 1));
// Create the check boxes.
JCheckBox iHardDrive = new JCheckBox("Install Hard Drive ($25.00)");
JCheckBox ram = new JCheckBox("Install Ram ($15.00)");
JCheckBox virus = new JCheckBox("Remove Virus ($50.00)");
JCheckBox fHardDrive = new JCheckBox("Format Hard Drive ($80.00)");
JCheckBox labourQuote = new JCheckBox("Hourly Labour Qoute ($10.00)");
//Add a border around the panel.
setBorder(BorderFactory.createTitledBorder("Standard Services"));
// Add the checkboxes to the panel.
add(iHardDrive);
add(ram);
add(virus);
add(fHardDrive);
add(labourQuote);
}
}
public class HourlyService extends JPanel {
public HourlyService() {
// Created grid layout with 2 rows, 1 column
setLayout(new GridLayout(2, 1));
// Create labels to display instructions.
JLabel cost = new JLabel("Parts Cost:");
JLabel labour = new JLabel("Hours of Labour:");
// Create two text fields 10 characters wide.
JTextField costTextField = new JTextField(10);
JTextField labourTextField = new JTextField(10);
// Place a 0 in the text fields.
costTextField.setText("0");
labourTextField.setText("0");
// Add a border around the layout
setBorder(BorderFactory.createTitledBorder("Hourly Service"));
// Add labels and text fields to the panel.
add(cost);
add(costTextField);
add(labour);
add(labourTextField);
}
}
}
Use the method pack() to remove unnecessary spaces..
Use it at as the last line.

How do I lay out Input panel with multiple textfields and OK, CANCEL buttons?

I am trying to achieve the following effect in Java:
However, I am not sure what layout to use and how. FlowLayout obviously doesn't work. GridLayout won't work either because the first 4 rows are supposed to be 1 column rows, but the 5th row needs to have 2 columns.
This is my code so far:
public class DepositPanel extends JPanel
{
private JLabel cashL, checksL;
private JTextField cashTF, checksTF;
private JButton ok, cancel;
DepositPanel()
{
JPanel depositP = new JPanel();
depositP.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));
depositP.setPreferredSize(new Dimension(250, 85));
JTextField cashTF = new JTextField(22);
JTextField checksTF = new JTextField(22);
JLabel cashL = new JLabel("Cash:");
JLabel checksL = new JLabel("Checks:");
ok = new JButton("OK");
cancel = new JButton("CANCEL");
depositP.add(cashL);
depositP.add(cashTF);
depositP.add(checksL);
depositP.add(checksTF);
depositP.add(ok);
depositP.add(cancel):
}
}
You could try with combinations of Layouts, 2 JPanels, 1 for buttons and 1 for fields, button panel with FlowLayout and fields panel with BoxLayout. And adding them to the frame. (I did a JFrame for testing, but you can change it to a JPanel and add that panel to your JFrame). Just be sure to have only 1 JFrame, see The use of multiple JFrames, Good / Bad Practice.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class DepositExample {
JFrame frame;
JPanel buttonPane, fieldsPanel;
JLabel cash, checks;
JTextField cashField, checksField;
JButton ok, cancel;
DepositExample() {
frame = new JFrame("Deposit");
buttonPane = new JPanel();
fieldsPanel = new JPanel();
cash = new JLabel("Cash");
checks = new JLabel("Checks");
cashField = new JTextField("");
checksField = new JTextField("");
ok = new JButton("OK");
cancel = new JButton("Cancel");
fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.PAGE_AXIS));
buttonPane.setLayout(new FlowLayout());
fieldsPanel.add(cash);
fieldsPanel.add(cashField);
fieldsPanel.add(checks);
fieldsPanel.add(checksField);
buttonPane.add(ok);
buttonPane.add(cancel);
frame.add(fieldsPanel, BorderLayout.PAGE_START);
frame.add(buttonPane, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new DepositExample();
}
}
To get some more spacing between components you can add EmptyBorders as recommended by #LuxxMiner in his comment below.
In this case you can use a JOptionPane to build a simple panel for you:
JTextField firstName = new JTextField(10);
JTextField lastName = new JTextField(10);
Object[] msg = {"First Name:", firstName, "Last Name:", lastName};
result = JOptionPane.showConfirmDialog(
frame,
msg,
"Use default layout",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.YES_OPTION)
{
System.out.println(firstName.getText() + " : " + lastName.getText());
}
else
{
System.out.println("Canceled");
}
The only problem with this approach is that the focus will be on a button, not the first name text field.
So to solve this problem you can check out the RequestFocusListener found in Dialog Focus which will cause focus to be placed on the first name text field once the dialog is displayed.
JTextField firstName = new JTextField(10);
firstName.addAncestorListener( new RequestFocusListener() );
Although for more complex layouts it is better to create one or more panels each using an appropriate layout manager for the requirement.
There are many ways to achieve a layout like this. The first thing you need to get used to, is that its often simpler to split up different requirements into different containers using different layout managers.
If you separate the two buttons into their own panel and treat that panel with the buttons as "just another line" in the window, you can basically just use a GridLayout with a single column. The panel with the buttons could then use a FlowLayout to place the buttons side by side.
Try this:
public class Window extends JFrame{
....
}
JLabel example;
//Constructor
public Window(){
example = new JLabel("Sample text");
example.setBounds(x,y,width,height)
//JComponent...
setLayout(null);
setSize(width,height);
setVisible(true);
}
Without the JPanel you can specify the x and y coordinates

positioning different component in java GUI

im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)
This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);

Java Swing simple center of JPanel in other JPanel

I have this incredibly easy task of wanting a nice centered JPanel inside another JPanel. The parent is set to 900, 550, and the child should be approximately 200,400 or so.
To do this, I thought giving the parent a BorderLayout and then setting the setPreferredSize(200, 400) of the child. This child would be in the CENTER. Two empty JPanels would be on the EAST and WEST. Of course this did not work. Giving the two sidepanels a setPreferredSize() of course DID work. Problem with this is that narrowing the Frame causes the center pane to go away.
Here's some sample code that should give show the issue:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Temporary {
public static Temporary myObj = null;
private JFrame mainFrame;
public void go(){
mainFrame = new JFrame("Swing");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setPreferredSize(new Dimension(900,550));
JPanel mainCards = new JPanel(new CardLayout());
mainCards.add(loginLayer(), "Login");
mainFrame.setContentPane(mainCards);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
public JPanel loginLayer(){
JPanel masterPane = new JPanel(new BorderLayout());
JPanel centerPane = new JPanel();
centerPane.setLayout(new BoxLayout(centerPane, BoxLayout.Y_AXIS));
centerPane.setPreferredSize(new Dimension(100,200));
JLabel label = new JLabel("Swing is overly");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(label);
JButton button = new JButton("complicated");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(button);
JTextField textField = new JTextField(10);
centerPane.add(textField);
JPanel filler = new JPanel();
JPanel filler2 = new JPanel();
masterPane.add(filler, BorderLayout.WEST);
masterPane.add(centerPane, BorderLayout.CENTER);
masterPane.add(filler2, BorderLayout.EAST);
return masterPane;
}
public static void main(String[] args){
myObj = new Temporary();
myObj.go();
}
}
BorderLayout will, by it's nature, give as much of the available space as it can to the CENTER component. This is how it's designed.
If you want the component to be centered within the parent container, BUT maintain it's preferred size, you should consider using a GridBagLayout instead. Without any additional constraints, this should achieve the result you're after
For example...
public JPanel loginLayer(){
JPanel masterPane = new JPanel(new GridBagLayout);
JPanel centerPane = new JPanel();
centerPane.setLayout(new BoxLayout(centerPane, BoxLayout.Y_AXIS));
JLabel label = new JLabel("Swing is overly");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(label);
JButton button = new JButton("complicated");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPane.add(button);
JTextField textField = new JTextField(10);
centerPane.add(textField);
masterPane.add(centerPane);
// Add additional borders to providing padding around the center pane
// as you need
return masterPane;
}
I would also avoid actively setting the preferred size of component in this way, as it's possible that the components you're adding to it will exceed your expectations, instead, make use of things like EmptyBorder (for example) to add additional white space arouond the component and it's contents
In Java Swing, you generally want to avoid creating a bunch of statically positioned items with preferred sizes and absolute positions, because things get weird with resizing (as you've noticed). Instead you want to rely on the fluid LayoutManagers. There is an excellent tutorial here. Or, if you want to supply a mock-up of some sort to show the actual UI you are trying to create, I could provide some more feedback.

I'm having trouble with Java Layout

This is my first GUI application and I'm having trouble making it look neat. I have tried several layouts and tinkered with them e.g flow, grid, border. When I run the program everything is just jumbled together.
I would like it to look like:
Unloaded Measurement |textfield| |textfield|
Loaded Rider Measurement |textField| |textfield|
Loaded Bike Measurement |textField| |Textfield|
|Button|
_______________________________________________________________________________________
Race Sag: |TextField|
Free Sag: |TextField|
Race Sag Notes: | TextField |
Free Sag Notes: | TextField |
Here is a screenshot to help understand what my issue is:
The top is for user input and the bottom is calculated output. I hope that I have given enough details for some help with this. I really appreciate anyone that helps out!
Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JLabel messageLabel;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JLabel raceSagLabel;
private JLabel freeSagLabel;
private JTextField wholeTextField;
private JTextField wholeTextField1;
private JTextField wholeTextField2;
private JTextField fracTextField;
private JTextField fracTextField1;
private JTextField fracTextField2;
private JTextField raceSagText;
private JTextField freeSagText;
private JTextField noteText;
private JTextField noteText1;
private JButton calcButton;
private final int WINDOW_WIDTH = 575;
private final int WINDOW_HEIGHT = 400;
/*===============================================================================
Project : test.java - SagCalculator
Author : Brian Green
Date : Jan 10, 2013
Abstract:
===============================================================================*/
public static void main(String[] args) {
#SuppressWarnings("unused")
Main sc = new Main();
}
public Main(){
setTitle("Rider Sag Calculator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout();
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel(){
messageLabel = new JLabel("Enter Unloaded Stand Measurement");
messageLabel1 = new JLabel("Enter Loaded with Rider Measurement");
messageLabel2 = new JLabel("Enter Loaed without Rider Measurement");
wholeTextField = new JTextField(3);
fracTextField = new JTextField(3);
wholeTextField1 = new JTextField(3);
fracTextField1 = new JTextField(3);
wholeTextField2 = new JTextField(3);
fracTextField2 = new JTextField(3);
calcButton = new JButton("Calculate");
raceSagLabel = new JLabel("Race Sag: ");
raceSagText = new JTextField(5);
freeSagLabel = new JLabel("Free Sag: ");
freeSagText = new JTextField(5);
noteText = new JTextField(30);
noteText1 = new JTextField(30);
calcButton.addActionListener(new CalcButtonListener());
panel = new JPanel();
panel.add(messageLabel);
panel.add(wholeTextField);
panel.add(fracTextField);
panel.add(messageLabel1);
panel.add(wholeTextField1);
panel.add(fracTextField1);
panel.add(messageLabel2);
panel.add(wholeTextField2);
panel.add(fracTextField2);
panel.add(calcButton);
panel.add(raceSagLabel);
panel.add(raceSagText);
panel.add(freeSagLabel);
panel.add(freeSagText);
panel.add(noteText);
panel.add(noteText1);
}
If for some reason you need to see more of the code, just let me know. I will be happy to provide it. Thanks for the help!
I got this all worked out! I would like to say thanks to #trashgod for his suggestion:
Try calling pack() on your JFrame, the layout doesn't get applied immediately when you set it. Alternatively, you can use validate(), which should lay out the component as well. Btw. in your sample code you don't set a layout manager.
It's possible to achieve the layout that you want with some of the other suggestions here (including GridBagLayout), but the easiest solution by far is to use the JGoodies FormLayout,
since it's explicitly designed for creating layouts where you need to line up fields and labels.
GroupLayout, see here, does a nice job on labeled forms, and it is manageable as a subpanel.

Categories

Resources