JTabbedPane panels won't line up correctly - java

I am attempting to make a JTabbedPane that can show all the field pertaining to an object (in this case a person) and all the inherent fields that go with it. In doing so i am attempting to have the first panel(the one I am currently having trouble with) contain name, phone number and email.
As you can see below, I placed the JLabels for the title of the row in one panel, and the JLabels for the information in the right panel. The issue with this is that they will not separate from each other. I would like the left labels to be left aligned and together they should take up the entirety of the available panel size. setAlignment didn't seem to have any effect.
This is the code for the text panel creation:
private static JComponent makeTextPanel(String text){
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1,1));
panel.add(filler);
return panel;
}
This is the code for TabbedPane as of this second:
public static void tabbedReadMenu(){
JFrame readMenu = new JFrame("Student Records");
JTabbedPane tabbedPane = new JTabbedPane();
Dimension d = new Dimension(300,300);
tabbedPane.setPreferredSize(d);
JComponent basicInfoPane = makeTextPanel("Basic Info");
tabbedPane.addTab("Basic Info", BasicInfoTab());
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
readMenu.add(tabbedPane);
readMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
readMenu.pack();
readMenu.setLocationRelativeTo(null);
readMenu.setVisible(true);
}
And this is the information for the actual tab along with the nested panels:
private static JPanel BasicInfoTab(){
JPanel basicInfoTab = new JPanel();
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
JPanel buttons = new JPanel();
JPanel spacing = new JPanel();
JPanel title = new JPanel();
JPanel mainPanel = new JPanel();
LayoutManager singleLine = new GridLayout(5,1);
leftPanel.setLayout(singleLine);
rightPanel.setLayout(singleLine);
buttons.setLayout(new FlowLayout());
mainPanel.setLayout(new SpringLayout());
spacing.setLayout(new GridLayout(3,1));
JLabel jspacing = new JLabel(" ");
JLabel jspacing1 = new JLabel(" ");
JLabel jspacing2 = new JLabel(" ");
spacing.add(jspacing);
spacing.add(jspacing1);
spacing.add(jspacing2);
spacing.setLayout(new FlowLayout());
JLabel header = new JLabel("Basic Student Information");
title.add(header);
JLabel FNLabel = new JLabel("First Name: "); //Creates all Labels
JLabel MILabel = new JLabel("Middle Initial: ");
JLabel LNLabel = new JLabel("Last Name: ");
JLabel IDLabel = new JLabel("Student ID: ");
JLabel EmailLabel = new JLabel("E-mail Address: ");
leftPanel.add(FNLabel);
leftPanel.add(MILabel);
leftPanel.add(LNLabel);
leftPanel.add(IDLabel);
leftPanel.add(EmailLabel);
selectedStudent = SaveFunction.passStudent();
JLabel FNInfo = new JLabel(selectedStudent.getFirstName());
JLabel MIInfo = new JLabel(selectedStudent.getMidInitial());
JLabel LNInfo = new JLabel(selectedStudent.getLastName());
JLabel IDInfo = new JLabel(selectedStudent.getID());
JLabel EmailInfo = new JLabel(selectedStudent.getEmail());
rightPanel.add(FNInfo);
rightPanel.add(MIInfo);
rightPanel.add(LNInfo);
rightPanel.add(IDInfo);
rightPanel.add(EmailInfo);
FNLabel.setHorizontalAlignment(JLabel.LEFT);
MILabel.setHorizontalAlignment(JLabel.LEFT);
LNLabel.setHorizontalAlignment(JLabel.LEFT);
IDLabel.setHorizontalAlignment(JLabel.LEFT);
EmailLabel.setHorizontalAlignment(JLabel.LEFT);
JButton edit = new JButton("Edit");
JButton close = new JButton("Close");
buttons.add(edit);
buttons.add(close);
basicInfoTab.add(title, BorderLayout.NORTH);
basicInfoTab.add(spacing, BorderLayout.CENTER);
basicInfoTab.add(leftPanel, BorderLayout.WEST);
basicInfoTab.add(rightPanel, BorderLayout.EAST);
basicInfoTab.add(buttons, BorderLayout.SOUTH);
return basicInfoTab;
}
Any help would be very much appreciated (including any more general coding tips on how I should improve).

Basically, for form design, I pretty much stick to GridBagLayout. If you don't mind a 3rd party layout, you should also consider MigLayout
Check out How to use GridBagLayout for more details...
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FormLayout {
public static void main(String[] args) {
new FormLayout();
}
public FormLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JLabel FNLabel = new JLabel("First Name: ");
JLabel MILabel = new JLabel("Middle Initial: ");
JLabel LNLabel = new JLabel("Last Name: ");
JLabel IDLabel = new JLabel("Student ID: ");
JLabel EmailLabel = new JLabel("E-mail Address: ");
JLabel FNInfo = new JLabel("My first name");
JLabel MIInfo = new JLabel("My initial");
JLabel LNInfo = new JLabel("My last name");
JLabel IDInfo = new JLabel("My student id");
JLabel EmailInfo = new JLabel("My Email");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.anchor = GridBagConstraints.WEST;
add(FNLabel, gbc);
gbc.gridy++;
add(MILabel, gbc);
gbc.gridy++;
add(LNLabel, gbc);
gbc.gridy++;
add(IDLabel, gbc);
gbc.gridy++;
add(EmailLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(FNInfo, gbc);
gbc.gridy++;
add(MIInfo, gbc);
gbc.gridy++;
add(LNInfo, gbc);
gbc.gridy++;
add(IDInfo, gbc);
gbc.gridy++;
add(EmailInfo, gbc);
}
}
}

Related

how can i center Label in frame Swing?

I want to make the copyright in the image below in the center of the frame.
I tried to add SwingConstants.CENTER and Component.CENTER_ALIGNMENT but neither worked.
Can someone please help me with this one? Thanks in advance.
enter image description here
This is my code:
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
JTextField text1;
JTextField text2;
JLabel label1;
JLabel label2;
JButton encrypt;
JButton decrypt;
JLabel copyright;
//constructor
public MyFrame(){
super("Encryption and Decryption");
setLayout(new FlowLayout()); //add first text field
label1 = new JLabel("enter a text: ");
add(label1);
text1= new JTextField(10);
add(text1);
//add second text field
label2 = new JLabel("result: ");
add(label2);
text2= new JTextField(10);
add(text2);
encrypt = new JButton("encrypt!");
add(encrypt);
decrypt = new JButton("decrypt!");
add(decrypt);
copyright = new JLabel(" © Project realized by Ayoub Touti ");
add(copyright);
//organizing elements in a panel
JPanel panel = new JPanel(new GridLayout(4,2,12,6));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(encrypt);
panel.add(decrypt);
panel.add(copyright);
add(panel);
}
}
//////////////////////////////
import javax.swing.*;
public class main {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (500, 200);
frame.setResizable(true);
frame.setVisible (true);
frame.setLocationRelativeTo(null); // to open the window in the main screen
}
}
Use a GridBagLayout (or a combination of layouts through compound components, slightly demonstrated below)
import java.awt.EventQueue;
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;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = gbc.LINE_END;
gbc.insets = new Insets(0, 8, 0, 8);
add(new JLabel("enter a text:"), gbc);
gbc.gridy++;
add(new JLabel("result:"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = gbc.LINE_START;
add(new JTextField(10), gbc);
gbc.gridy++;
add(new JTextField(10), gbc);
JPanel actionPane = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = gbc.HORIZONTAL;
gbc.insets = new Insets(0, 0, 0, 0);
actionPane.add(new JButton("encyprt!"), gbc);
gbc.gridx++;
actionPane.add(new JButton("decyprt!"), gbc);
gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
gbc.gridy = 2;
add(actionPane, gbc);
gbc.gridy++;
add(new JLabel("© Project realized by Ayoub Touti"), gbc);
}
}
}
See How to Use GridBagLayout for more details

How to control where in my window or JFrame panels appear

this has seriously been the biggest issue in my code. I just want to create a simple pizza order taker using multiple panels. I want to be able to dictate the specific area each panel is located. Can someone please just pretend I'm a complete idiot and help me point this out?
I've attached my code as well as an image of how it looks so far. I want to be able to place individual segments like getting the user's information, choosing pizza size, then toppings, then a section where I will display the receipt with all of the order total.
I can do the calculations and take in values, I just need to figure out the appearance.
import javax.swing.*;
import java.awt.*;
public class PIZZA extends JFrame {
Container window = getContentPane();
ButtonGroup ordertype;
JRadioButton delivery, takeout;
JRadioButton small, medium, large;
JLabel fname, phonenum, zipcode;
JTextField ufname, uphonenum, uzipcode;
JPanel userinfoinput;
JPanel delivery_type;
JPanel userinfolabel;
JButton start;
BoxLayout userbox, labelbox, deliverybox;
ImageIcon starticon = new ImageIcon("start.png");
public PIZZA() {
}
public static void main(String[] args){
PIZZA frame = new PIZZA();
new PIZZA();
frame.setSize(new Dimension(600,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("KRUSTY KRAB PIZZA");
frame.deliverymethod();
frame.getuserinfo();
frame.userinfolabels();
frame.getpizzasize();
frame.toppings_meat();
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
private void deliverymethod(){
delivery_type = new JPanel();
ordertype = new ButtonGroup();
delivery = new JRadioButton("Delivery (Currently Unavailable)");
delivery.setEnabled(false);
takeout = new JRadioButton("Take Out");
ordertype.add(takeout);
ordertype.add(delivery);
delivery_type.add(takeout);
delivery_type.add(delivery);
delivery_type.setSize(100,100);
window.add(delivery_type,BorderLayout.NORTH);
}
private void getuserinfo(){
userinfoinput = new JPanel();
//start = new JButton("Start", starticon);
//start.setLayout(null);
ufname = new JTextField(12);
uphonenum = new JTextField(12);
uzipcode = new JTextField(12);
userinfoinput.add(ufname);
userinfoinput.add(uphonenum);
userinfoinput.add(uzipcode);
//userinfoinput.add(start);
GridLayout lay = new GridLayout(3,1);
userinfoinput.setLayout(lay);
window.add(userinfoinput, BorderLayout.CENTER);
}
private void userinfolabels(){
userinfolabel = new JPanel();
fname = new JLabel("First Name");
phonenum = new JLabel("Phone Number");
zipcode = new JLabel("Zip Code");
userinfolabel.add(fname);
userinfolabel.add(zipcode);
userinfolabel.add(phonenum);
labelbox = new BoxLayout(userinfolabel, BoxLayout.Y_AXIS);
GridLayout label = new GridLayout(3,1);
userinfolabel.setLayout(label);
window.add(userinfolabel, BorderLayout.CENTER);
}
private void getpizzasize(){
JPanel pizzasize = new JPanel();
ButtonGroup size = new ButtonGroup();
small = new JRadioButton("Small");
medium = new JRadioButton("Medium");
large = new JRadioButton("Large");
size.add(small);
size.add(medium);
size.add(large);
pizzasize.add(small);
pizzasize.add(medium);
pizzasize.add(large);
pizzasize.setLayout(new FlowLayout());
pizzasize.setSize(100,100);
window.add(pizzasize, BorderLayout.SOUTH);
}
private void toppings_meat(){
JPanel meat = new JPanel();
meat.setLayout(new BoxLayout(meat, BoxLayout.Y_AXIS));
JCheckBox pepperoni = new JCheckBox("Pepperoni");
JCheckBox meatball = new JCheckBox("Meatball");
JCheckBox chicken = new JCheckBox("Grilled Chicken");
JCheckBox sausage = new JCheckBox("Italian Sausage");
JCheckBox bacon = new JCheckBox("Bacon");
meat.add(pepperoni);
meat.add(meatball);
meat.add(chicken);
meat.add(sausage);
meat.add(bacon);
window.add(meat);
}
}
This pizza GUI uses several Swing layout managers in different JPanels.
The main layout managers that I want to talk about are the JFrame BorderLayout and the input form GridBagLayout.
A BorderLayout is rather flexible in that you can put Swing components in various locations. The JPanels I created for this GUI are in the BEFORE_FIRST_LINE, CENTER, AFTER_LAST_LINE, and AFTER_LINE_ENDS positions of the BorderLayout.
The input form uses a GridBagLayout to position the JLabels and the input JTextFields in a column. The GridBagLayout is more flexible than a GridLayout because the grid cells don't have to be the same size in a GridBagLayout.
The Oracle Swing tutorial A Visual Guide to Layout Managers shows the different Swin layout managers, and how to use them.
Here's the code I used to create the pizza GUI. I created each subordinate JPanel in a separate method. All of the JFrame code is in the run method. Separating different parts of the GUI allows me to focus on one part of the GUI at a time. I can test each JPanel method separately.
I create the Swing components from left to right, top to bottom within a JPanel. This allows me to visually verify that I've included all the appropriate methods for a component. This also allows me to zero in on any component that isn't correct.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PizzaOrdering implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PizzaOrdering());
}
#Override
public void run() {
JFrame frame = new JFrame("KRUSTY KRAB PIZZA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getDeliveryMethodPanel(),
BorderLayout.BEFORE_FIRST_LINE);
frame.add(getUserInformationPanel(),
BorderLayout.CENTER);
frame.add(getPizzaSizePanel(),
BorderLayout.AFTER_LAST_LINE);
frame.add(getMeatToppingsPanel(),
BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getDeliveryMethodPanel() {
JPanel deliveryMethodPanel = new JPanel(new FlowLayout());
ButtonGroup orderTypeGroup = new ButtonGroup();
JRadioButton takeoutRadioButton =
new JRadioButton("Take Out");
orderTypeGroup.add(takeoutRadioButton);
deliveryMethodPanel.add(takeoutRadioButton);
JRadioButton deliveryRadioButton =
new JRadioButton("Delivery (Currently Unavailable)");
deliveryRadioButton.setEnabled(false);
orderTypeGroup.add(deliveryRadioButton);
deliveryMethodPanel.add(deliveryRadioButton);
return deliveryMethodPanel;
}
private JPanel getUserInformationPanel() {
JPanel userInformationPanel = new JPanel(new GridBagLayout());
userInformationPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1d;
JLabel nameLabel = new JLabel("First Name:");
userInformationPanel.add(nameLabel, gbc);
gbc.gridx++;
JTextField userNameField = new JTextField(20);
userInformationPanel.add(userNameField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel phoneNumberLabel = new JLabel("Phone Number:");
userInformationPanel.add(phoneNumberLabel, gbc);
gbc.gridx++;
JTextField userPhoneNumberField = new JTextField(20);
userInformationPanel.add(userPhoneNumberField, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel zipCodeLabel = new JLabel("Zip Code:");
userInformationPanel.add(zipCodeLabel, gbc);
gbc.gridx++;
JTextField userZipCodeField = new JTextField(20);
userInformationPanel.add(userZipCodeField, gbc);
return userInformationPanel;
}
private JPanel getPizzaSizePanel() {
JPanel pizzaSizePanel = new JPanel(new FlowLayout());
ButtonGroup sizeGroup = new ButtonGroup();
JRadioButton smallRadioButton = new JRadioButton("Small");
sizeGroup.add(smallRadioButton);
pizzaSizePanel.add(smallRadioButton);
JRadioButton mediumRadioButton = new JRadioButton("Medium");
sizeGroup.add(mediumRadioButton);
pizzaSizePanel.add(mediumRadioButton);
JRadioButton largeRadioButton = new JRadioButton("Large");
sizeGroup.add(largeRadioButton);
pizzaSizePanel.add(largeRadioButton);
return pizzaSizePanel;
}
private JPanel getMeatToppingsPanel() {
JPanel meatToppingsPanel = new JPanel();
meatToppingsPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
meatToppingsPanel.setLayout(new BoxLayout(
meatToppingsPanel, BoxLayout.Y_AXIS));
JCheckBox pepperoniCheckBox = new JCheckBox("Pepperoni");
meatToppingsPanel.add(pepperoniCheckBox);
JCheckBox meatballCheckBox = new JCheckBox("Meatball");
meatToppingsPanel.add(meatballCheckBox);
JCheckBox chickenCheckBox = new JCheckBox("Grilled Chicken");
meatToppingsPanel.add(chickenCheckBox);
JCheckBox sausageCheckBox = new JCheckBox("Italian Sausage");
meatToppingsPanel.add(sausageCheckBox);
JCheckBox baconCheckBox = new JCheckBox("Bacon");
meatToppingsPanel.add(baconCheckBox);
return meatToppingsPanel;
}
}

Java Swing - JPanel centering issue

Basically, this is the structure of my Window.
The actual window looks like this:
My problem is that I want the MainPanel with the ComboBox and and the rest to fit the JFrame window. Stretch horizontally and stick to the top. But I've tried all kinds of layouts (Box, GridBag, Grid). It just remains centered. How do I achieve this?
Here is the MVCC:
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class simplelayout{
JFrame mainFrame;
JPanel mainPanel;
JPanel innerPanel;
JPanel createDomainPanel;
JPanel listDomainPanel = new JPanel(new GridBagLayout());
String comboBoxItems[]={"Create Domain","List Domains"};
#SuppressWarnings("rawtypes")
JComboBox listCombo;
JButton goBtn;
CardLayout layout;
JTextField domainName = new JTextField();
JLabel successMessage = new JLabel("");
public simplelayout(){
initialize();
setCardLayout();
}
#SuppressWarnings({ "rawtypes", "unchecked" })
private void setCardLayout() {
innerPanel = new JPanel();
//innerPanel.setSize(600, 400);
layout = new CardLayout(10,10);
innerPanel.setLayout(layout);
//Default Panel
JPanel defaultPanel = new JPanel(new FlowLayout());
defaultPanel.add(new JLabel("Welcome to Amazon Simple DB"));
//Create Domain Panel
createDomainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//createDomainPanel.setSize(600, 300);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.gridx=0;
gbc.gridy=0;
createDomainPanel.add(new JLabel("Enter the name of the domain"), gbc);
gbc.gridx=0;
gbc.gridy=1;
createDomainPanel.add(domainName, gbc);
JPanel result = new JPanel(new FlowLayout());
result.add(successMessage);
gbc.anchor=GridBagConstraints.LAST_LINE_START;
gbc.gridx=0;
gbc.gridy=2;
createDomainPanel.add(result, gbc);
//List Domain Panel
listDomainPanel.add(new JLabel("List of Domains"), gbc);
//Add to innerPanel
innerPanel.add(defaultPanel, "Default");
innerPanel.add(createDomainPanel, "Create Domain");
innerPanel.add(listDomainPanel, "List Domain");
layout.show(innerPanel, "Default");
DefaultComboBoxModel panelName = new DefaultComboBoxModel();
panelName.addElement("Create Domain");
panelName.addElement("List Domain");
listCombo = new JComboBox(panelName);
listCombo.setSelectedIndex(0);
JScrollPane listComboScroll = new JScrollPane(listCombo);
goBtn = new JButton("Go");
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.fill=GridBagConstraints.HORIZONTAL;
gbc1.anchor=GridBagConstraints.FIRST_LINE_START;
gbc1.gridx = 0;
gbc1.gridx = 0;
mainPanel.add(listComboScroll, gbc1);
gbc1.gridy = 1;
mainPanel.add(goBtn, gbc1);
gbc1.gridy = 2;
mainPanel.add(innerPanel, gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.fill=GridBagConstraints.HORIZONTAL;
gbc2.anchor=GridBagConstraints.FIRST_LINE_START;
JScrollPane scr = new JScrollPane(mainPanel);
mainPanel.setSize(mainFrame.getPreferredSize());
mainFrame.add(scr, gbc);
mainFrame.setVisible(true);
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
private void initialize() {
mainFrame = new JFrame("Amazon Simple DB");
mainFrame.setSize(700, 500);
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
//mainPanel.setLayout(new GridLayout(8,1));
mainFrame.setVisible(true);
}
public static void main(String[] args) {
try {
//UIManager.put("nimbusBase", new Color(178,56,249));
//UIManager.put("nimbusBlueGrey", new Color(102,212,199));
//UIManager.put("control", new Color(212,133,102));
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new simplelayout();
}
});
}
}
It sounds like you want to use the application frame's default BorderLayout, placing the combobox & button components in a nested panel in the BorderLayout.PAGE_START location with the innerPanel in the CENTER position.
Try to add a mainFrame.pack(); in the initialize() and the setCardLayout()methods, Remove all mainFrame.setSize() and mainPanel.setSize() methods.

Align 2 sets/items on either side of center

I'm trying to figure out the best way to align 2 sets of items in the center of a panel in a Java Swing application. The panel is in the North position of a BorderLayout whose width is determined by the JTextField in the Center position of the layout. The problem I'm having is, I have a set of labels and smaller text fields that I want to center so that the end of the label and the start of the first text field meet at the center of the panel.
I've tried GroupLayout, but ended up with the following result:
Note: The 2 text fields separated by a + are in a sub-panel.
What I'm trying to achieve is the following:
Apparently I'm either missing something, or this is far more complicated than necessary to do. I actually run into this issue a LOT! I'm surprised there isn't a special grid layout specifically for this.
Trying to do this with a GridLayout resulted in this:
So... what IS the easiest way to get the layout I'm looking for (second image)?
GroupLayout example code below:
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
frame.setContentPane(panel);
JPanel longText = new JPanel();
JPanel shortText = new JPanel();
JPanel mediumText = new JPanel();
longText.add(new TextField(5));
longText.add(new JLabel("+"));
longText.add(new TextField(5));
shortText.add(new TextField(5));
shortText.add(new JLabel("+"));
shortText.add(new TextField(5));
mediumText.add(new TextField(5));
mediumText.add(new JLabel("+"));
mediumText.add(new TextField(5));
JLabel lExample = new JLabel("Long text example:");
JLabel sExample = new JLabel("Short:");
JLabel mExample = new JLabel("Medium Example:");
JPanel subPanel = new JPanel();
GroupLayout layout = new GroupLayout(subPanel);
subPanel.setLayout(layout);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(lExample)
.addComponent(sExample)
.addComponent(mExample))
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(longText)
.addComponent(shortText)
.addComponent(mediumText))))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(lExample)
.addComponent(longText))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(sExample)
.addComponent(shortText))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(mExample).addComponent(mediumText))
);
JTextArea textArea = new JTextArea() {
#Override
public Dimension getPreferredSize() {
return new Dimension(600,300);
}
};
textArea.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAutoscrolls(true);
panel.add(subPanel,BorderLayout.NORTH);
panel.add(textArea,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
Consider using a GridBagLayout, as it gives you a lot more control over the placement of individual components and respects the preferred size of the components where it can (unless you override them through the use of the GridBagConstraints)
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutExample {
public static void main(String[] args) {
new LayoutExample();
}
public LayoutExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JLabel longText = new JLabel("Long Text Example");
JLabel shortText = new JLabel("Short Example");
JLabel medText = new JLabel("Medium Example");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(longText, gbc);
addFields(gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.EAST;
add(shortText, gbc);
addFields(gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.EAST;
add(medText, gbc);
addFields(gbc);
}
protected void addFields(GridBagConstraints gbc) {
JTextField field1 = new JTextField("0", 5);
field1.setEnabled(false);
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx++;
add(field1, gbc);
gbc.gridx++;
gbc.insets = new Insets(0, 4, 0, 4);
add(new JLabel("+"), gbc);
JTextField field2 = new JTextField(5);
gbc.gridx++;
add(field2, gbc);
}
}
}

Put 4 JLabel at corners of a JFrame

As the title said, I'm trying to put 4 different JLabels at each of the corners of a JFrame. I want them to stay there forever even if I try to resize the JFrame
I've tried using a layout manager but I just can't get it right.
ImageIcon icon;
JLabel labelNW = new JLabel();
JLabel labelNE = new JLabel();
JLabel labelSW = new JLabel();
JLabel labelSE = new JLabel();
URL buttonURL = InputOutputTest.class.getResource("images/square_dot.gif");
if(buttonURL != null){
icon = new ImageIcon(buttonURL);
labelNW.setIcon(icon);
labelNE.setIcon(icon);
labelSW.setIcon(icon);
labelSE.setIcon(icon);
}
window.add(labelNW, BorderLayout.NORTH);
//window.add(labelNE, BorderLayout.EAST);
//window.add(labelSW, BorderLayout.WEST);
window.add(labelSE, BorderLayout.SOUTH);
This code takes care of the north and south of the left side. I'm probably approaching this wrong though.
I also tried GridLayout (2,2) but they weren't at the corners and there's a huge gap on the right side.
You will want to nest JPanels each using its own layout. In fact you could do this by nesting JPanels that all use BorderLayout.
Going to check if GridBagLayout can do it in one shot.... hang on...
Yep GridBagLayout does it too:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class GridBagExample {
public static void main(String[] args) {
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(
0, 0, 0, 0), 0, 0);
mainPanel.add(new JLabel("Left Upper"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHEAST;
mainPanel.add(new JLabel("Right Upper"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.SOUTHWEST;
mainPanel.add(new JLabel("Left Lower"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.SOUTHEAST;
mainPanel.add(new JLabel("Right Lower"), gbc);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
Edit
Now for the BorderLayout example:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JPanel northPanel = new JPanel(new BorderLayout());
northPanel.add(new JLabel("North East"), BorderLayout.EAST);
northPanel.add(new JLabel("North West"), BorderLayout.WEST);
JPanel southPanel = new JPanel(new BorderLayout());
southPanel.add(new JLabel("South East"), BorderLayout.EAST);
southPanel.add(new JLabel("South West"), BorderLayout.WEST);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(northPanel, BorderLayout.NORTH);
mainPanel.add(southPanel, BorderLayout.SOUTH);
JFrame frame = new JFrame("BorderLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
I find that only GroupLayout gives me the control I need for precisely laid out components. This should do the trick. You need to make sure the gap in between has a very large Maximum value (i.e. Short.MAX_VALUE), but you can set the minimum and preferred sizes to whatever you want.
public class LabelFrame extends JFrame {
public LabelFrame() {
JPanel contentPane = new JPanel();
JLabel labelNW = new JLabel();
JLabel labelNE = new JLabel();
JLabel labelSW = new JLabel();
JLabel labelSE = new JLabel();
URL buttonURL = InputOutputTest.class.getResource("images/square_dot.gif");
if(buttonURL != null){
icon = new ImageIcon(buttonURL);
labelNW.setIcon(icon);
labelNE.setIcon(icon);
labelSW.setIcon(icon);
labelSE.setIcon(icon);
}
GroupLayout layout = new GroupLayout(contentPane);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(labelNW)
.addComponent(labelSW))
.addGap(20,50,Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(labelNE)
.addComponent(labelSE))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(labelNW)
.addComponent(labelNE))
.addGap(20,50,Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(labelSW)
.addComponent(labelSE))
);
contentPane.setLayout(layout);
setContentPane(contentPane);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
LabelFrame frame = new LabelFrame();
frame.setVisible(true);
}
});
}
}
I've tried using a layout manager..
Layout managers are wonderful at what they do, but are perhaps the wrong tool for this job. Consider using a custom border instead. Here is an example.

Categories

Resources