Java checkbox positioning - java

I'm relatively new to Java and I am creating a login form. The problem I am having is the position of the checkbox seen in the picture below, I am trying to assign it to start directly below the "P" in "Password.
Here is the code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Login extends JPanel{
private static JLabel usernameLabel, passwordLabel;
private static JTextField usernameField;
private static JPasswordField passwordField;
private static JCheckBox checkBox;
private static JButton loginButton;
GridBagConstraints gbc = new GridBagConstraints();
public Login(){
//layout
setLayout(new GridBagLayout());
//spacing between each component
gbc.insets = new Insets(1,1,1,1);
//new instance of objects
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
checkBox = new JCheckBox("Keep me logged in");
loginButton = new JButton("Login");
//username label
gbc.anchor = GridBagConstraints.LINE_END;
gbc.gridx = 0;
gbc.gridy = 0;
add(usernameLabel, gbc);
//password label
gbc.gridx = 0;
gbc.gridy = 1;
add(passwordLabel, gbc);
//username textfield
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 1;
gbc.gridy = 0;
add(usernameField, gbc);
//password textfield
gbc.gridx = 1;
gbc.gridy = 1;
add(passwordField, gbc);
//keep logged in checkbox
gbc.gridx = 0;
gbc.gridy = 2;
add(checkBox, gbc);
//login button
gbc.gridx = 1;
gbc.gridy = 3;
add(loginButton, gbc);
}
}
I'm not sure why the checkbox isn't in-line with the labels, any help will be appreciated. Thanks.

try this:
checkBox = new JCheckBox("");
checkBoxLabel = new JLabel("Keep me logged in");
Then when you are adding your components
//keep logged in checkbox
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.WEST;
add(checkBox, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
add(checkBoxLabel);

You have to set the fill Property of GridBagConstraints
//username label
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill=GridBagConstraints.BOTH;//this will do the trick

Related

Can't close JFrame, from click inside JPanel

I have the following situation:
I have a JFrame(GridBagLayout) with 3 JPanels in it (headerPanel, bodyPanel, footerPanel);
On the bodyPanel I have a login button;
What I want, is to close the JFrame, an open another one;
Main:
package com.system.reservation.airline;
public class Main {
public static void main(String[] args) { // Main function that executes the program
LoginPage loginPage = new LoginPage();
}
}
LoginPage:
public class LoginPage extends JFrame{
HeaderPanel headerPanel = new HeaderPanel();
BodyPanel bodyPanel = new BodyPanel();
FooterPanel footerPanel = new FooterPanel();
public LoginPage(){ // Constructor
this.setTitle("Login"); // Frame title
this.setSize(400, 600); // Frame size
this.setLocationRelativeTo(null); // Center frame, when launched
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Frame function, on close button (will close)
this.getContentPane().setBackground(new Color(240,248,255)); // Light blue
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
this.add(headerPanel, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 1;
this.add(bodyPanel, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridheight = 3;
this.add(footerPanel, gbc);
this.pack();
this.setVisible(true); // Frame visible
}
}
BodyPanel:
package com.system.reservation.airline.panels;
import com.system.reservation.airline.HomePage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BodyPanel extends JPanel implements ActionListener { // Listens to events
JButton login_button;
JTextField userName_txb, password_txb;
JLabel tokenResponse;
String username;
String password;
public void setUsername(String newUsername){
username = newUsername;
}
public String getUsername(){
return username;
}
public void setPassword(String newPassword){
password = newPassword;
}
public String getPassword(){
return password;
}
public BodyPanel(){
Color transparent = new Color(1f,0f,0f,0f);
this.setBackground(transparent);
this.setLayout(new BorderLayout());
//this.setBorder(BorderFactory.createLineBorder(Color.green, 3));
//------------ Login Panel ------------------------
JPanel login_panel = new JPanel(new BorderLayout());
login_panel.setBackground(transparent);
login_panel.setPreferredSize(new Dimension(400, 50));
//login_panel.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 5));
JLabel login_label = new JLabel();
login_label.setText("Login");
login_label.setHorizontalAlignment(JLabel.CENTER);
login_label.setFont(new Font("Arial", Font.PLAIN, 20));
login_panel.add(login_label, BorderLayout.CENTER);
//------------ Login Panel ------------------------
//------------ Input Panel ------------------------
JPanel input_fields_panel = new JPanel(new GridBagLayout());
input_fields_panel.setBackground(transparent);
//input_fields_panel.setPreferredSize(new Dimension(400, 150));
//input_fields_panel.setBorder(BorderFactory.createLineBorder(Color.black, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
//-------------
JLabel userName_label = new JLabel("Username: ");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.insets = new Insets(0,10,0,0);
input_fields_panel.add(userName_label, gbc);
userName_txb = new JTextField();
userName_txb.setPreferredSize(new Dimension(250,30));
gbc.gridx = 3;
gbc.insets = new Insets(5,0,5,20);
input_fields_panel.add(userName_txb, gbc);
//-------------
//-------------
JLabel password_label = new JLabel("Password: ");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.insets = new Insets(0,10,0,0);
input_fields_panel.add(password_label, gbc);
password_txb = new JTextField();
password_txb.setPreferredSize(new Dimension(250,30));
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.insets = new Insets(5,0,5,20);
input_fields_panel.add(password_txb, gbc);
//-------------
//------ Login Button -----------
login_button = new JButton("Login");
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 4;
gbc.gridheight = 1;
gbc.insets = new Insets(10,150,5,150);
login_button.addActionListener(this);
input_fields_panel.add(login_button, gbc);
//------ Login Button -----------
tokenResponse = new JLabel("");
tokenResponse.setHorizontalAlignment(JLabel.CENTER);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 4;
gbc.gridheight = 1;
gbc.insets = new Insets(0,0,0,0);
input_fields_panel.add(tokenResponse, gbc);
//------------ Input Panel ------------------------
//-------------------------------------
this.add(login_panel, BorderLayout.NORTH);
this.add(input_fields_panel, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == login_button) {
System.out.println("Olá");
//-------------------------
if(userName_txb.getText().replaceAll("\\s+","").equals("") || password_txb.getText().replaceAll("\\s+","").equals("")){ // removes white spaces
// If either of the text fields are empty, a label is displayed
System.out.println("It's empty!");
tokenResponse.setText("The input fields are empty!");
} else {
String userName_value = userName_txb.getText();
String userPassword_value = password_txb.getText();
// User inputs are stored
setUsername(userName_value);
setPassword(userPassword_value);
// User inputs are initialized
//-----------------------
try{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_login", "root", "***********");
// Connect to the database;
Statement statement = connection.createStatement();
// It will initiate a command;
ResultSet resultSet = statement.executeQuery("select customer_username, customer_password from user_authentication");
// Execute the command; // column // table
while (resultSet.next()){ // While there are results, it will print them;
String name = resultSet.getString("customer_username");
String password = resultSet.getString("customer_password");
if(!getUsername().equals(name) || !getPassword().equals(password)){
tokenResponse.setText("The username or the password are incorrect!");
System.out.println("It does not match!");
//break;
} else {
// CLOSE JFRAME
System.out.println("It matches!");
HomePage homePage = new HomePage();
break;
}
}
}catch(Exception e2){
e2.printStackTrace();
}
}
}
}
}
After I click login the JFrame on the left shows up.
I want to close the one on the right.
Any help would be appreciated, thanks.
Answer from #camickr, managed to close Jframe, from click inside Jpanel:
login_button = (JButton) e.getSource();
SwingUtilities.windowForComponent(login_button).dispose();

JRadioButton is not show properly

I want to create a simple food ordering system, now i'm creating the interface of an order form. I used GridBagLayout for create the form layout, my problem is when I want to assign 3 radio button in same row, it's only show me 1 of the button....I hope somebody can help me pls....
Here is my java code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
/**
*
* #author user
*/
public class ChickenChopOrderingSystem
{
JFrame frame;
JPanel mainPanel, p1, p2, p3, p4;
JLabel lblTitle, lblName, lblPhoneNum, lblFlavour, lblChickenPart;
JTextField txtName, txtPhoneNum;
String flavour[] = {"Black Pepper Sauce", "Hainanese", "Grilled", "Lemon"};
JComboBox box;
ButtonGroup bg = new ButtonGroup();
JRadioButton btnWhole, btnHalf, btnQuarter;
JButton btnDone, btnExit;
public ChickenChopOrderingSystem()
{
frame = new JFrame("Chicken Chop Ordering System");
mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(700,700));
mainPanel.setBackground(Color.yellow);
lblName = new JLabel("Customer's Name: ");
txtName = new JTextField(20);
lblPhoneNum = new JLabel("Phone Number: ");
txtPhoneNum = new JTextField(11);
lblChickenPart = new JLabel("Select Part of Chicken: ");
btnWhole = new JRadioButton("Whole");
btnWhole.addItemListener(new OperationListener());
btnHalf = new JRadioButton("Half");
btnHalf.addItemListener(new OperationListener());
btnQuarter = new JRadioButton("Quarter");
btnQuarter.addItemListener(new OperationListener());
bg.add(btnWhole);
bg.add(btnHalf);
bg.add(btnQuarter);
lblFlavour = new JLabel("Select a flavour: ");
box = new JComboBox(flavour);
btnDone = new JButton("Done");
btnExit = new JButton("Exit");
btnExit.addActionListener(new ButtonListener());
//GridBaglayout
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//Label
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
mainPanel.add(lblName, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.5;
mainPanel.add(lblPhoneNum, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 0.5;
mainPanel.add(lblChickenPart, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.weightx = 0.5;
mainPanel.add(lblFlavour, gbc);
//TextField
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 3;
mainPanel.add(txtName, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 3;
mainPanel.add(txtPhoneNum, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 2;
mainPanel.add(btnWhole, gbc);
gbc.gridx = 2;
gbc.gridy = 2;
mainPanel.add(btnHalf, gbc);
gbc.gridx = 3;
gbc.gridy = 2;
mainPanel.add(btnHalf, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 3;
mainPanel.add(box, gbc);
//frame setting
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(mainPanel, new GridBagConstraints());
frame.setSize(new Dimension(1000, 1000));
frame.setVisible(true);
}
public class OperationListener implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getSource() == btnWhole)
{
if (ie.getStateChange() == ItemEvent.SELECTED)
{
box.removeAllItems();
box.addItem(flavour[2]);
}
} if (ie.getSource() == btnHalf)
{
if (ie.getStateChange() == ItemEvent.SELECTED)
{
box.removeAllItems();
box.addItem(flavour[0]);
box.addItem(flavour[2]);
box.addItem(flavour[3]);
}
} if (ie.getSource() == btnQuarter)
{
if (ie.getStateChange() == ItemEvent.SELECTED)
{
box.removeAllItems();
box.addItem(flavour[0]);
box.addItem(flavour[1]);
box.addItem(flavour[3]);
}
}
}
}
public class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == btnExit)
{
int s = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?",
"Exit", JOptionPane.YES_NO_OPTION);
if (s == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
}
public static void main(String[] args)
{
ChickenChopOrderingSystem run = new ChickenChopOrderingSystem();
}
}
Click here to view output
For something like this:
Use this code:
import java.awt.*;
import javax.swing.*;
public class ChickenChopOrderingSystem {
JFrame frame;
JPanel mainPanel, p1, p2, p3, p4;
JLabel lblTitle, lblName, lblPhoneNum, lblFlavour, lblChickenPart;
JTextField txtName, txtPhoneNum;
String flavour[] = {"Black Pepper Sauce", "Hainanese", "Grilled", "Lemon"};
JComboBox box;
ButtonGroup bg = new ButtonGroup();
JRadioButton btnWhole, btnHalf, btnQuarter;
JButton btnDone, btnExit;
public ChickenChopOrderingSystem() {
frame = new JFrame("Chicken Chop Ordering System");
mainPanel = new JPanel();
// GUESSWORK!
//mainPanel.setPreferredSize(new Dimension(700,700));
mainPanel.setBackground(Color.yellow);
lblName = new JLabel("Customer's Name: ");
txtName = new JTextField(20);
lblPhoneNum = new JLabel("Phone Number: ");
txtPhoneNum = new JTextField(11);
lblChickenPart = new JLabel("Select Part of Chicken: ");
btnWhole = new JRadioButton("Whole");
btnHalf = new JRadioButton("Half");
btnQuarter = new JRadioButton("Quarter");
bg.add(btnWhole);
bg.add(btnHalf);
bg.add(btnQuarter);
lblFlavour = new JLabel("Select a flavour: ");
box = new JComboBox(flavour);
btnDone = new JButton("Done");
btnExit = new JButton("Exit");
//GridBaglayout
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
int s = 20;
gbc.insets = new Insets(s,s,s,s);
//Label
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
mainPanel.add(lblName, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.5;
mainPanel.add(lblPhoneNum, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 0.5;
mainPanel.add(lblChickenPart, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.weightx = 0.5;
mainPanel.add(lblFlavour, gbc);
//TextField
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 3;
mainPanel.add(txtName, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 3;
mainPanel.add(txtPhoneNum, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.weightx = 1d/6d;
mainPanel.add(btnWhole, gbc);
gbc.gridx = 2;
gbc.gridy = 2;
mainPanel.add(btnHalf, gbc);
gbc.gridx = 3;
gbc.gridy = 2;
mainPanel.add(btnQuarter, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 3;
mainPanel.add(box, gbc);
//frame setting
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(mainPanel, new GridBagConstraints());
// GUESSWORK!
//frame.setSize(new Dimension(1000, 1000));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ChickenChopOrderingSystem run = new ChickenChopOrderingSystem();
}
}
The problems in the original code were many. (Trawling memory..)
The constraints of the last element were not set back to grid width of 3, confusing the layout manager.
The ItemListener was doing strange stuff with removing components, don't do that.
The preferred size of the panel, and the size of the frame, were guesswork. Use pack() to have the correct size calculated. (Add a standard Inserts to the initial constraints for white space.)

GridBagLayout - Vertically positioning components

Trying to align a form next to my JTable with GridBagLayout and I am struggling to get my components to the top of the panel. I need the price label and fields just underneath the item label and field but I cannot get it to move from the bottom of the panel.
If I use anchor = GridConstraints.NORTHWEST, this moves the item label and field to the top, but then I lose the ability to anchor it with LINE_END. Unless there is a way to do both? Please see my image where I have attempted to demonstrate the area I want to place my form. Appreciate any help.
GridBagConstraints gbc = new GridBagConstraints();
// TEST COMPONENTS
JLabel lblItem = new JLabel("Item: ");
JLabel lblPrice = new JLabel("Price: ");
JLabel lblQuantity = new JLabel ("Quantity: ");
JTextField itemField = new JTextField(15);
JTextField pricePoundsField = new JTextField(3);
JTextField pricePenceField = new JTextField(2);
JTextField quantityField = new JTextField(3);
gbc.gridx = 0;
gbc.gridy = 0;
//gbc.weightx = 1.0;
//gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.LINE_START;
panelStockTable.add(jsp, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
panelStockTable.add(lblItem, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panelStockTable.add(lblPrice, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 2;
gbc.gridy = 0;
panelStockTable.add(itemField, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
panelStockTable.add(pricePoundsField, gbc);
The more complex a UI becomes, the more you want to focus on isolating the functionality and layouts to their own containers/classes.
This is where the concept of compounding layouts becomes very powerful. Rather then laying the fields out directly onto the same container as the table, use a separate container for them
Here, the right panel is standing in for the table and the blue panel is demonstrating the compounding container...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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 Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JPanel stockTableProxy = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 150);
}
};
stockTableProxy.setBackground(Color.RED);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.LINE_START;
add(stockTableProxy, gbc);
JPanel fieldsPanel = new JPanel(new GridBagLayout());
fieldsPanel.setBackground(Color.BLUE);
// TEST COMPONENTS
JLabel lblItem = new JLabel("Item: ");
JLabel lblPrice = new JLabel("Price: ");
JLabel lblQuantity = new JLabel("Quantity: ");
JTextField itemField = new JTextField(15);
JTextField pricePoundsField = new JTextField(3);
JTextField pricePenceField = new JTextField(2);
JTextField quantityField = new JTextField(3);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
fieldsPanel.add(lblItem, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
fieldsPanel.add(lblPrice, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 2;
gbc.gridy = 0;
fieldsPanel.add(itemField, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
fieldsPanel.add(pricePoundsField, gbc);
gbc.gridx = 0;
gbc.gridy = 20;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
fieldsPanel.add(new JLabel(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.VERTICAL;
add(fieldsPanel, gbc);
}
}
}
But wait, there is more...
gbc.gridx = 0;
gbc.gridy = 20;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
fieldsPanel.add(new JLabel(), gbc);
This is a little trick you can use to force component to move to different edges of the container, here, I've used it to push all the fields to the top of the container.
All it does is add a transparent component (in this a JLabel) and provides all the left over space to it, neat

Radio buttons group with both options enabled

I already made a button group for gender, but still both radio buttons were being enabled. I tried interchanging the group of gender to yearlevel. The yearlevel does fine and still the gender both radio buttons being enabled.
here's my code:
public class myFirstGUI extends JFrame {
JPanel panel = new JPanel();
JLabel lblName = new JLabel("Name:");
JLabel lblyl = new JLabel("Year Level:");
JLabel lblCourse = new JLabel("Course:");
JLabel lblProg = new JLabel("Program:");
JLabel lblGender = new JLabel("Gender:"); //Gender
JTextField txtName = new JTextField();
JButton btnSubmit = new JButton("Submit");
JButton btnReset = new JButton("Reset");
GridBagLayout gLayout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JComboBox cboProgram = new JComboBox();
JRadioButton rbtn1 = new JRadioButton("1st");
JRadioButton rbtn2 = new JRadioButton("2nd");
JRadioButton rbtn3 = new JRadioButton("3rd");
JRadioButton rbtn4 = new JRadioButton("4th");
JRadioButton rbtn5 = new JRadioButton("5th");
JRadioButton rbtnM = new JRadioButton("Male"); //Gender Male
JRadioButton rbtnF = new JRadioButton("Female"); //Gender Female
JCheckBox chk003a = new JCheckBox("ITE003A");
JCheckBox chk003 = new JCheckBox("CPE003");
JCheckBox chk201 = new JCheckBox("CS201");
ButtonGroup bg = new ButtonGroup();
ButtonGroup bg1 = new ButtonGroup();
public void setYearLevel() {
bg1.add(rbtn1);
bg1.add(rbtn2);
bg1.add(rbtn3);
bg1.add(rbtn4);
bg1.add(rbtn5);
}
public void setGender() { //Gender
bg.add(rbtnM);
bg.add(rbtnF);
}
public void setProgram() {
cboProgram.addItem("CPE");
cboProgram.addItem("IE");
cboProgram.addItem("ECE");
}
public myFirstGUI() {
setYearLevel();
setProgram();
setSize(300, 500);
panel.setBackground(Color.CYAN);
setTitle("My First GUI");
add(panel);
panel.setLayout(gLayout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 10;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(lblName, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(txtName, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(lblGender, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(rbtnM, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
panel.add(rbtnF, gbc);
rbtnM.setBackground(Color.cyan);
rbtnF.setBackground(Color.cyan);
gbc.gridx = 0;
gbc.gridy = 3;
panel.add(lblProg, gbc);
gbc.gridx = 1;
gbc.gridy = 3;
panel.add(cboProgram, gbc);
chk003a.setBackground(Color.cyan);
chk003.setBackground(Color.cyan);
chk201.setBackground(Color.cyan);
gbc.gridx = 0;
gbc.gridy = 4;
panel.add(lblCourse, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
panel.add(chk003a, gbc);
gbc.gridx = 1;
gbc.gridy = 5;
panel.add(chk003, gbc);
gbc.gridx = 1;
gbc.gridy = 6;
panel.add(chk201, gbc);
gbc.gridx = 0;
gbc.gridy = 7;
panel.add(lblyl, gbc);
gbc.gridx = 1;
gbc.gridy = 7;
panel.add(rbtn1, gbc);
gbc.gridx = 1;
gbc.gridy = 8;
panel.add(rbtn2, gbc);
gbc.gridx = 1;
gbc.gridy = 9;
panel.add(rbtn3, gbc);
gbc.gridx = 1;
gbc.gridy = 10;
panel.add(rbtn4, gbc);
gbc.gridx = 1;
gbc.gridy = 11;
panel.add(rbtn5, gbc);
rbtn1.setBackground(Color.cyan);
rbtn2.setBackground(Color.cyan);
rbtn3.setBackground(Color.cyan);
rbtn4.setBackground(Color.cyan);
rbtn5.setBackground(Color.cyan);
gbc.gridx = 0;
gbc.gridy = 12;
panel.add(btnReset, gbc);
gbc.gridx = 1;
gbc.gridy = 12;
panel.add(btnSubmit, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(myFirstGUI.this, "Welcome " + txtName.getText() +
"\nProgram " + cboProgram.getSelectedItem() +
"\nYear Level: " + getYL());
}
});
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtName.setText("");
bg.clearSelection();
bg1.clearSelection();
cboProgram.setSelectedIndex(0);
}
});
}
public String getYL() {
if (rbtn1.isSelected())
return "1st";
else if (rbtn2.isSelected())
return "2nd";
else if (rbtn3.isSelected())
return "3rd";
else if (rbtn4.isSelected())
return "4th";
else if (rbtn5.isSelected())
return "5th";
else
return "Please select your level";
}
public static void main(String[] args) {
new myFirstGUI().show();
}
}
I am not sure if you have pasted an incomplete code here or not as I Don't see a call to setGender() function from your program. Since the radio buttons are not assigned to the button group, that can cause the problem.
If you are asking why your JRadioButton for Male are Female are both being selected, this is what you can do.
ButtonGroup group = new ButtonGroup();
group.add(btnM);
group.add(btnF);
You need to group the radio buttons which belong to the same category (group).
After adding them to a group, only one JRadioButton will be selected.

how to add a TiltledBorder in a GridBagLayout?

I am trying to make an UI with Swing using only one Container with the GridBagLayout !
My problem is that I want to regroup some JtextFields and Jlabels under one title (TitledBorder) in my interface, is there a way to add the border directly in my container, or should I create another JPanel to regroup my components and then add the hole Panel to my GridBagLayout ?
Based on the pic you provided, the typical solution would be to have 2 separate panels, each with their own TitledBorder, and then place both of these panels on a third outer panel.
However, you could create a similar effect on a single panel by replacing the TitledBorders with a combination of a JLabel followed by a JSeparator.
The difference is that the logical "group" of fields is now only defined by title that isn't surrounding the whole group. Some people prefer this, others do not.
Here's a sample of your pic to give you the idea:
import java.awt.*;
import javax.swing.*;
public class Test implements Runnable
{
private JTextField firstName;
private JTextField lastName;
private JTextField title;
private JTextField nickname;
private JComboBox format;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Test());
}
public Test()
{
firstName = new JTextField(20);
lastName = new JTextField(20);
title = new JTextField(20);
nickname = new JTextField(20);
format = new JComboBox();
}
public void run()
{
JFrame frame = new JFrame();
frame.getContentPane().add(createPanel());
frame.pack();
frame.setVisible(true);
}
private JPanel createPanel()
{
JPanel p = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4,4,4,4);
gbc.ipadx = 1;
gbc.ipady = 1;
gbc.anchor = GridBagConstraints.WEST;
JLabel nameHeader = new JLabel("Name:");
nameHeader.setForeground(Color.RED.darker());
p.add(nameHeader, gbc);
gbc.gridx = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
p.add(new JSeparator(JSeparator.HORIZONTAL), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
p.add(new JLabel("First Name"), gbc);
gbc.gridx = 1;
p.add(firstName, gbc);
gbc.gridx = 2;
p.add(new JLabel("Last Name"), gbc);
gbc.gridx = 3;
p.add(lastName, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
p.add(new JLabel("Title"), gbc);
gbc.gridx = 1;
p.add(title, gbc);
gbc.gridx = 2;
p.add(new JLabel("Nickname"), gbc);
gbc.gridx = 3;
p.add(nickname, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
p.add(new JLabel("Format"), gbc);
gbc.gridx = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
p.add(format, gbc);
return p;
}
}
You could play with the constraints to polish this up a bit, but you get the idea.
An upside to this approach is that when adding more fields for the Email section, you can get them to line up with the fields in the Name section. With separate panels, this would be more difficult (you could use a bunch of Box.createHorizontalStrut(...) for this).
The downside to this approach is that you now have a large panel with many fields, and it could get a bit unwieldy to maintain if you need to add more fields.
Try This :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
class SwingLayoutDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;
public SwingLayoutDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();
swingLayoutDemo.showGridBagLayoutDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setBorder(new TitledBorder (
new LineBorder (Color.black, 5),
"Title String"));
controlPanel.add(new JLabel("TitledBorder using LineBorder"));
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showGridBagLayoutDemo(){
headerLabel.setText("Layout in action: GridBagLayout");
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setSize(300,300);
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JButton("Button 1"),gbc);
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(new JButton("Button 2"),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(new JButton("Button 3"),gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(new JButton("Button 4"),gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
panel.add(new JButton("Button 5"),gbc);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}

Categories

Resources