import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
public class LoginApplet extends JApplet { /**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Username", "Password"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[2];
jtf = new JTextField[2];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
for(int i=0; i<labeltxt.length; i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
}
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
}
Hi guys.. This code I have posted up is from class LoginApplet which gets called by an ActionPerformed from another class.... I had no problem with it set as JFrame (the rubric for this assignment was in JApplet). Now when I converted it to JApplet problems show up. I am not familiar with JApplet, and is there anything wrong with the code showing up as blank when ran?
Get rid of
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
It's preventing the applet from thinking it's visible...
Related
I am trying to create 2 sets of JLabels, one set would include a name and the second set would include values. The values get pulled from a database and get displayed to the second set of JLabels.
I cant seem how to line up the 2 sets of JLabels so that the set with the names would be on the left side of the panel and the set with the values would be directly to the right. I know my gridlayout has a factor in it I just dont know what it should be.
package Frames;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import Application.Main;
public class AccountFrame extends JPanel implements PropertyChangeListener, ActionListener {
private static JFrame accountFrame;
private JLabel firstNameLabel;
private JLabel lastNameLabel;
private JLabel dobLabel;
private JLabel emailLabel;
private JLabel usernameLabel;
private JLabel passwordLabel;
private static String firstNameLabelText = "First Name: ";
private static String lastNameLabelText = "Last Name: ";
private static String dobLabelText = "Date Of Birth: ";
private static String emailLabelText = "Email: ";
private static String usernameLabelText = "Username: ";
private static String passwordLabelText = "Password: ";
private static JButton editButton;
private static JButton closeButton;
public AccountFrame() {
super(new BorderLayout());
firstNameLabel = new JLabel(firstNameLabelText);
firstNameLabel.setForeground(Color.WHITE);
firstNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
lastNameLabel = new JLabel(lastNameLabelText);
lastNameLabel.setForeground(Color.WHITE);
lastNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
dobLabel = new JLabel(dobLabelText);
dobLabel.setForeground(Color.WHITE);
dobLabel.setFont(new Font("Andalus", Font.BOLD, 18));
emailLabel = new JLabel(emailLabelText);
emailLabel.setForeground(Color.WHITE);
emailLabel.setFont(new Font("Andalus", Font.BOLD, 18));
usernameLabel = new JLabel(usernameLabelText);
usernameLabel.setForeground(Color.WHITE);
usernameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
passwordLabel = new JLabel(passwordLabelText);
passwordLabel.setForeground(Color.WHITE);
passwordLabel.setFont(new Font("Andalus", Font.BOLD, 18));
editButton = new JButton("Edit");
editButton.setBackground(new Color(129,13,13));
editButton.setForeground(Color.WHITE);
editButton.setFocusPainted(false);
editButton.setFont(new Font("Andalus", Font.BOLD, 18));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//EDIT ACCOUNT INFORMATION.
}
});
closeButton = new JButton("Close");
closeButton.setBackground(new Color(129,13,13));
closeButton.setForeground(Color.WHITE);
closeButton.setFocusPainted(false);
closeButton.setFont(new Font("Andalus", Font.BOLD, 18));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountFrame.dispose();
}
});
TitledBorder accountPanelBorder = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.WHITE), "Account", TitledBorder.CENTER , TitledBorder.TOP, new Font("Andalus", Font.BOLD, 18));
accountPanelBorder.setTitleColor(Color.WHITE);
//this is where the labels need to have values
//added on to the string to get values from the current character.
JPanel accountPanel = new JPanel(new GridLayout(0, 1));
accountPanel.add(firstNameLabel, BorderLayout.WEST);
accountPanel.add(lastNameLabel, BorderLayout.WEST);
accountPanel.add(dobLabel, BorderLayout.WEST);
accountPanel.add(emailLabel, BorderLayout.WEST);
accountPanel.add(usernameLabel, BorderLayout.WEST);
accountPanel.add(passwordLabel, BorderLayout.WEST);
accountPanel.setBackground(new Color(82,80,80));
accountPanel.setBorder(accountPanelBorder);
accountPanel.setPreferredSize(new Dimension(400,200));
// JPanel accountValuesPanel = new JPanel(new GridLayout(0, 1));
// accountValuesPanel.add(firstNameValue);
// accountValuesPanel.setBackground(new Color(82,80,80));
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttons.add(editButton);
buttons.add(closeButton);
buttons.setBackground(new Color(82,80,80));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
setBackground(new Color(82,80,80));
add(accountPanel, BorderLayout.WEST);
add(buttons, BorderLayout.SOUTH);
// add(accountValuesPanel, BorderLayout.LINE_END);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
public static void createAndShowGUI() {
accountFrame = new JFrame("OVERRATED");
accountFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
accountFrame.setBackground(Color.red);
accountFrame.add(new AccountFrame());
accountFrame.setVisible(true);
accountFrame.pack();
accountFrame.setLocationRelativeTo(null);
accountFrame.setTitle("OVERRATED");
accountFrame.setResizable(false);
//startupFrame.setIconImage(new ImageIcon().getImage());
JFrame.setDefaultLookAndFeelDecorated(false);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
AccountFrame a = new AccountFrame();
a.createAndShowGUI();
}
}
First of all, even though your accountPanel layout is gridLayout, you have used it is BorderLayout:
JPanel accountPanel = new JPanel(new GridLayout(0, 1));
accountPanel.add(firstNameLabel, BorderLayout.WEST); // BorderLayout.WEST wrong
My suggestion, You should use gridbaglayout for it. GridbagLayout may look difficult to learn but it is actually quite logic.
I have changed your code a little bit.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class AccountFrame extends JPanel implements PropertyChangeListener,
ActionListener {
private static JFrame accountFrame;
private JTextField firstNameTextField, lastNameTextField, dobTextField,
emailTextField, userNameTextField;
private JPasswordField passwordPasswordField;
private JLabel firstNameLabel;
private JLabel lastNameLabel;
private JLabel dobLabel;
private JLabel emailLabel;
private JLabel usernameLabel;
private JLabel passwordLabel;
private static String firstNameLabelText = "First Name: ";
private static String lastNameLabelText = "Last Name: ";
private static String dobLabelText = "Date Of Birth: ";
private static String emailLabelText = "Email: ";
private static String usernameLabelText = "Username: ";
private static String passwordLabelText = "Password: ";
private static JButton editButton;
private static JButton closeButton;
public AccountFrame() {
super(new BorderLayout());
firstNameLabel = new JLabel(firstNameLabelText);
firstNameLabel.setForeground(Color.WHITE);
firstNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
lastNameLabel = new JLabel(lastNameLabelText);
lastNameLabel.setForeground(Color.WHITE);
lastNameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
dobLabel = new JLabel(dobLabelText);
dobLabel.setForeground(Color.WHITE);
dobLabel.setFont(new Font("Andalus", Font.BOLD, 18));
emailLabel = new JLabel(emailLabelText);
emailLabel.setForeground(Color.WHITE);
emailLabel.setFont(new Font("Andalus", Font.BOLD, 18));
usernameLabel = new JLabel(usernameLabelText);
usernameLabel.setForeground(Color.WHITE);
usernameLabel.setFont(new Font("Andalus", Font.BOLD, 18));
passwordLabel = new JLabel(passwordLabelText);
passwordLabel.setForeground(Color.WHITE);
passwordLabel.setFont(new Font("Andalus", Font.BOLD, 18));
// lets create JTextFields and a JPasswordField
firstNameTextField = new JTextField(20);
lastNameTextField = new JTextField(20);
dobTextField = new JTextField(20);
emailTextField = new JTextField(20);
userNameTextField = new JTextField(20);
passwordPasswordField = new JPasswordField(20);
editButton = new JButton("Edit");
editButton.setBackground(new Color(129, 13, 13));
editButton.setForeground(Color.WHITE);
editButton.setFocusPainted(false);
editButton.setFont(new Font("Andalus", Font.BOLD, 18));
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// EDIT ACCOUNT INFORMATION.
}
});
closeButton = new JButton("Close");
closeButton.setBackground(new Color(129, 13, 13));
closeButton.setForeground(Color.WHITE);
closeButton.setFocusPainted(false);
closeButton.setFont(new Font("Andalus", Font.BOLD, 18));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
accountFrame.dispose();
}
});
TitledBorder accountPanelBorder = BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.WHITE), "Account",
TitledBorder.CENTER, TitledBorder.TOP, new Font("Andalus",
Font.BOLD, 18));
accountPanelBorder.setTitleColor(Color.WHITE);
// this is where the labels need to have values
// added on to the string to get values from the current character.
JPanel accountPanel = new JPanel(new GridBagLayout());
accountPanel.setBackground(new Color(82, 80, 80));
accountPanel.setBorder(accountPanelBorder);
accountPanel.setPreferredSize(new Dimension(400, 200));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(0, 0, 0, 0);
// lets add labels and textfields
// 1. row
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(firstNameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(firstNameTextField, gbc);
// 2. row
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(lastNameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(lastNameTextField, gbc);
// 3. row
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(dobLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(dobTextField, gbc);
// 4. row
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(emailLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(emailTextField, gbc);
// 5. row
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(usernameLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(userNameTextField, gbc);
// 6. row
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 1;
gbc.gridheight = 1;
accountPanel.add(passwordLabel, gbc);
gbc.gridx = 1;
gbc.gridwidth = 2;
accountPanel.add(passwordPasswordField, gbc);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttons.add(editButton);
buttons.add(closeButton);
buttons.setBackground(new Color(82, 80, 80));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
setBackground(new Color(82, 80, 80));
add(accountPanel, BorderLayout.WEST);
add(buttons, BorderLayout.SOUTH);
// add(accountValuesPanel, BorderLayout.LINE_END);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
*/
public static void createAndShowGUI() {
accountFrame = new JFrame("OVERRATED");
accountFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
accountFrame.setBackground(Color.red);
accountFrame.add(new AccountFrame());
accountFrame.pack();
accountFrame.setTitle("OVERRATED");
accountFrame.setResizable(false);
accountFrame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
AccountFrame a = new AccountFrame();
a.createAndShowGUI();
}
}
Your issue is that your GridLayout only has 1 column. You need to create your GridLayout like this: new GridLayout(0, 2). Below is a small runnable example that lays out pairs of JLabels right next to each other.
public static void main(String[] args) {
JFrame f = new JFrame("Good day");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 250);
JPanel panel = new JPanel(new GridLayout(0, 2));
JLabel left = new JLabel("Foo");
JLabel right = new JLabel(("Bar"));
JLabel hello = new JLabel("Hello");
JLabel world = new JLabel("World");
panel.add(left);
panel.add(right);
panel.add(hello);
panel.add(world);
f.add(panel);
f.setVisible(true);
}
Edited to make the code work
This might get closed a a dupe, anyway.
I'm trying to create an application for an assignment. I could just do the easy thing and use multiple JFrames but I don't want to do that.
I want an application with a login screen, a customer screen and an admin screen. I though I could just use JPanels and swap them as required, I can remove the login panel but can't add the customer panel.
Curently, the application starts as expected with the login JPanel
But when I click on ok, it's supposed to close the JPanel and open the customer Jpanel, instead it just closes the login panel.
package projFlight;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.UIManager;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class GUIMain {
GUIMainEvent event = new GUIMainEvent(this);
JFrame frame;
GUILoginScreen login = new GUILoginScreen();
GUICustomerScreen custScreen = new GUICustomerScreen();
/**
* Launch the application.
*/
public static void main(String[] args) {
GUIMain window = new GUIMain();
window.frame.setVisible(true);
}
/**
* Create the application.
*/
public GUIMain() {
setLookAndFeel();
initialize();
controller.start();
}
// The thread controlling changes of panels in the main window.
private Thread controller = new Thread() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.getContentPane().add(login);
addLogo(login);
frame.revalidate();
}
});
}
};
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.BLUE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
frame.setBounds(100, 100, 406, 473);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void addLogo(JPanel panel) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("C:\\Users\\Phil\\workspace\\projFlight\\Pictures\\WolfLogo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//The below line was causing the issue
//frame.getContentPane().setLayout(null);
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picLabel.setBounds(0, 0, 170, 128);
panel.add(picLabel);
//frame.getContentPane().add(login);
login.btnOk.addActionListener(event); //These also shouldn't be here
login.btnCancel.addActionListener(event); //These also shouldn't be here
}
// method to set the look and feel of the GUI
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// ignore error
}
}
}
/**
*
*/
package projFlight;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
/**
* #author Phil
*
*/
public class GUIMainEvent implements ActionListener{
GUIMain gui;
GUIMainEvent(GUIMain in) {
gui = in;
}
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
Object source = event.getSource();
if (source == gui.login.btnOk) {
gui.frame.getContentPane().remove(gui.login);
gui.frame.repaint();
gui.frame.getContentPane().add(gui.custScreen);
gui.custScreen.setVisible(true);
gui.frame.repaint();
gui.frame.revalidate();
} else if (source == gui.login.btnCancel) {
System.exit(0);
}
}
}
package projFlight;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class GUILoginScreen extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField tboUsername;
JPasswordField passwordField;
JButton btnOk;
JButton btnCancel;
/**
* Create the panel.
*/
public GUILoginScreen() {
setBackground(Color.DARK_GRAY);
setLayout(null);
setLookAndFeel();
JLabel lblUsername = new JLabel("Username");
lblUsername.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
lblUsername.setBounds(77, 170, 109, 35);
add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
lblPassword.setBounds(77, 235, 109, 35);
add(lblPassword);
tboUsername = new JTextField();
tboUsername.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
tboUsername.setBounds(77, 203, 241, 31);
add(tboUsername);
tboUsername.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
passwordField.setBounds(77, 268, 241, 31);
add(passwordField);
btnOk = new JButton("OK");
btnOk.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
btnOk.setBounds(77, 349, 109, 35);
add(btnOk);
btnCancel = new JButton("Cancel");
btnCancel.setFont(new Font("Segoe UI Black", Font.ITALIC, 18));
btnCancel.setBounds(209, 349, 109, 35);
add(btnCancel);
}
// method to set the look and feel of the GUI
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// ignore error
}
}
}
package projFlight;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
public class GUICustomerScreen extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Create the panel.
*/
String firstName = "Phil";
public GUICustomerScreen() {
setLayout(null);
JLabel lblHello = new JLabel("Hello " + firstName);
lblHello.setFont(new Font("Segoe UI Black", Font.ITALIC, 14));
lblHello.setBounds(184, 11, 107, 27);
add(lblHello);
}
}
I though I could just use JPanels and swap them as required,
You can use a CardLayout to do this.
Check out the section from the Swing tutorial on How to Use CardLayout for a working demo.
You should not use a multiple JFrame. You will encounter a lot of error. Try this use JDialog for your login frame and use GridBagLayout to make your components flexible. setBounds it not flexible sometimes it make components crumbled.
GridBagLayout: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
Sample Code
public class Login extends JDialog{
MainLoginFrame mainloginframe = new MainLoginFrame();
//Constructor
public Login(){
setSize(330,150);
setTitle("Login Sample");
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
getContentPane().add(mainloginframe);
}
public class MainLoginFrame extends JPanel{
//Create Labels
JLabel usernameLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
//Create TextField
JTextField usernameTextField = new JTextField(10);
JPasswordField passwordPasswordField = new JPasswordField(10);
//Create Button
JButton loginButton = new JButton("Login");
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");
//Create ComboBox
String[] selectUser = {"Administrator","Registrar"};
JComboBox listUser = new JComboBox(selectUser);
//Constraints
GridBagConstraints usernameLabelConstraints = new GridBagConstraints();
GridBagConstraints passwordLabelConstraints = new GridBagConstraints();
GridBagConstraints userTypeConstraints = new GridBagConstraints();
GridBagConstraints usernameTfConstraints = new GridBagConstraints();
GridBagConstraints passwordPfConstraints = new GridBagConstraints();
GridBagConstraints loginConstraints = new GridBagConstraints();
GridBagConstraints clearConstraints = new GridBagConstraints();
GridBagConstraints exitConstraints = new GridBagConstraints();
//Constructor
public MainLoginFrame(){
setLayout(new GridBagLayout());
usernameLabelConstraints.anchor = GridBagConstraints.LINE_START;
usernameLabelConstraints.weightx = 0.5;
usernameLabelConstraints.weighty = 0.5;
add(usernameLabel,usernameLabelConstraints);
passwordLabelConstraints.anchor = GridBagConstraints.LINE_START;
passwordLabelConstraints.weightx = 0.5;
passwordLabelConstraints.weighty = 0.5;
passwordLabelConstraints.gridx = 0;
passwordLabelConstraints.gridy = 1;
add(passwordLabel,passwordLabelConstraints);
usernameTfConstraints.anchor = GridBagConstraints.LINE_START;
usernameTfConstraints.weightx = 0.5;
usernameTfConstraints.weighty = 0.5;
usernameTfConstraints.gridx = 1;
usernameTfConstraints.gridy = 0;
add(usernameTextField,usernameTfConstraints);
passwordPfConstraints.anchor = GridBagConstraints.LINE_START;
passwordPfConstraints.weightx = 0.5;
passwordPfConstraints.weighty = 0.5;
passwordPfConstraints.gridx = 1;
passwordPfConstraints.gridy = 1;
add(passwordPasswordField,passwordPfConstraints);
userTypeConstraints.anchor = GridBagConstraints.LINE_START;
userTypeConstraints.weightx = 0.5;
userTypeConstraints.weighty = 0.5;
userTypeConstraints.gridx = 1;
userTypeConstraints.gridy = 2;
add(listUser,userTypeConstraints);
loginConstraints.anchor = GridBagConstraints.LINE_START;
loginConstraints.weightx = 0.5;
loginConstraints.weighty = 0.5;
loginConstraints.gridx = 1;
loginConstraints.gridy = 3;
add(loginButton,loginConstraints);
clearConstraints.anchor = GridBagConstraints.LINE_START;
clearConstraints.weightx = 0.5;
clearConstraints.weighty = 0.5;
clearConstraints.gridx = 2;
clearConstraints.gridy = 3;
add(clearButton,clearConstraints);
exitConstraints.anchor = GridBagConstraints.LINE_START;
exitConstraints.weightx = 0.5;
exitConstraints.weighty = 0.5;
exitConstraints.gridx = 3;
exitConstraints.gridy = 3;
add(exitButton,exitConstraints);
}
Here is what I have:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.LineBorder;
public class Main {
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
static JScrollPane scrollPane;
public static void main(String[] args) {
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
//frame.setPreferredSize(new Dimension(990, 990));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
//GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
//frameConstraints.gridx = 0;
//frameConstraints.gridy = 0;
//frame.add(addButton, frameConstraints);
frame.add(addButton);
// Construct panel
panel.setPreferredSize(new Dimension(1000, 1000));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(600, 600));
// Add panel to frame
//frameConstraints.gridx = 0;
//frameConstraints.gridy = 1;
//frameConstraints.weighty = 1;
//frame.add(panel, frameConstraints);
frame.add(scrollPane);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// Clear panel
panel.removeAll();
// Create label and text field
//JTextField jTextField = new JTextField();
//jTextField.setSize(100, 200);
//listOfTextFields.add(jTextField);
listOfLabels.add(new JLabel("" + indexer));
// Create constraints
//GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer; i++) {
// Text field constraints
//textFieldConstraints.gridx = 1;
//textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
//textFieldConstraints.weightx = 0.5;
//textFieldConstraints.insets = new Insets(10, 10, 10, 10);
//textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(0, 0, 0, 0);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
//panel.add(listOfTextFields.get(i), textFieldConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
c.ipady = 0;
panel.add(new JLabel(), c);
System.out.println("indexer is " + indexer);
// Increment indexer
indexer++;
panel.updateUI();
if(indexer ==2){
listOfLabels.set(0, new JLabel("Test"));
}
}
private int getWidth() {
// TODO Auto-generated method stub
return 0;
}
}
}
Here is the output:
What Am I doing wrong? I want the labels to be justified all the way to the left. I don't have any padding set to the left so I am confused.
FYI, I found this code on stackoverflow and my goal is to have labels that I can dynamically add and update, hence I commented out the textboxes.
Don't call setPreferredSize on the scroll pane, this isn't what you should setting, use GridBagConstraints weightx/y and fill properties.
Don't call updateUI, it doesn't do what you think it does, call revalidate instead, if you have to
The main reasons you're having problems is
You're call setPreferredSize on the panel. When adding components to a GridBagLayout, it will attempt to lay out components around the centre of the container
You've not specified a weightx or anchor property for the GridBagConstraints when adding the labels
I'm watching a youtube tutorial series by mybringback. (38th video in the series). At the very bottom of the code, I have e.getactioncommand. When I click on the radio button, I want it to say something in the text field. For instance when I hit radio button 1, it should say "you selected radio button 1" in the text field. I followed the tutorial exactly, but I can't figure out what's wrong.
I have the driver class as well. that i didn't post here.
Here;s the video https://www.youtube.com/watch?v=pjS_IiNp008&list=SPDAA5DE54FB5215EC
package ActionCommandnActionListeners;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FirstWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
String s;
JCheckBox cb, cb2;
JTextField textField;
JLabel label;
JRadioButton b1, b2, b3, b4;
ButtonGroup group;
JTextArea tb;
public FirstWindow() {
super("Your Computer is very special");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel(new GridBagLayout());
JPanel p4 = new JPanel();
b1 = new JRadioButton("Choice 1");
b1.setActionCommand("you selected num1");
b1.addActionListener(this);
b2 = new JRadioButton("Choice 2");
b2.setActionCommand("you selected num2");
b2.addActionListener(this);
b3 = new JRadioButton("Choice 3");
b3.setActionCommand("you selected num3");
b3.addActionListener(this);
b4 = new JRadioButton("Choice 4");
b4.setActionCommand("you selected num4");
b4.addActionListener(this);
group = new ButtonGroup();
group.add(b1);
group.add(b2);
group.add(b3);
group.add(b4);
p4.add(b1);
p4.add(b2);
p4.add(b3);
p4.add(b4);
JButton b = new JButton("Button 1");
JButton c = new JButton("Button 2");
p.add(b);
p.add(c);
cb = new JCheckBox("Do you LOVE bacon?");
cb2 = new JCheckBox("Do you LOVE cheese?");
p2.add(cb);
p2.add(cb2);
label = new JLabel("This is a label");
JTextArea tb = new JTextArea("This is a text area");
textField = new JTextField("text field");
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s2 = textField.getText();
label.setText(s2);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.gridx = 0;
gbc.gridy = 0;
p3.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
p3.add(tb, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
p3.add(textField, gbc);
add(p, BorderLayout.SOUTH);
add(p2, BorderLayout.NORTH);
add(p3, BorderLayout.CENTER);
add(p4, BorderLayout.WEST);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
s = "Good job kid, you harvested your corn! \n";
if (cb.isSelected()) {
s += " And of course you love bacon! \n";
}
if (cb2.isSelected()) {
s += " Most naturally you love cheese! \n";
}
JOptionPane.showMessageDialog(null, s);
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
tb.setText(e.getActionCommand());
}
}
JTextArea tb = new JTextArea("This is a text area");
You are shadowing your variables. You defined the "tb" variable as an instance variable and a local variable. You don't want the local variable because your actionPerformed() method can't reference local variables.
So the code should be:
//JTextArea tb = new JTextArea("This is a text area");
tb = new JTextArea("This is a text area");
I'm watching a youtube tutorial series by mybringback
I've never quite figured out why people use youtube for tutorials.
I would start with the Swing tutorial. This way not only can you read the tutorial at your pace but you can actually download the code and compile and test and change the code. So you start with working code and then you customize it to do what you want.
I'm using GridBagLayout to place my GUI components by the following code, wanting the components lay one by one in a column, without any gaps :
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestGUI extends JFrame{
public TestGUI(){
JPanel bigPanel = new JPanel(new GridBagLayout());
JPanel panel_a = new JPanel();
JButton btnA = new JButton("button a");
panel_a.add(btnA);
JPanel panel_b = new JPanel();
JButton btnB = new JButton("button b");
panel_b.add(btnB);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weighty = 1D;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTH;
bigPanel.add(panel_a, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
bigPanel.add(panel_b, c);
this.add(bigPanel);
}
public static void main(String[] args) {
TestGUI gui = new TestGUI();
gui.setVisible(true);
gui.pack();
}
}
I wish the panels will be shown one by one in the column. but now i got this :
As i am going to add some more components in the bigPanel, and required some more customization to the layout, so i need to use GridBagLayout instead of other Layout.
You need to add an extra component so that it will fill the rest of the available space and push the two button-panels to the top. When you will add more components, you can of course remove that component.
Another option (without requiring an extra component) would have been to set weighty=1.0 for the panel_b and anchor=NORTH, but then you would have to change that when you add more components.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGUI extends JFrame {
public TestGUI() {
JPanel bigPanel = new JPanel(new GridBagLayout());
JPanel panel_a = new JPanel();
JButton btnA = new JButton("button a");
panel_a.add(btnA);
JPanel panel_b = new JPanel();
JButton btnB = new JButton("button b");
panel_b.add(btnB);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
bigPanel.add(panel_a, c);
bigPanel.add(panel_b, c);
c.weighty = 1.0;
// Temporary panel to fill the rest of the bigPanel
bigPanel.add(new JPanel(), c);
this.add(bigPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestGUI gui = new TestGUI();
gui.pack();
gui.setVisible(true);
}
});
}
}