Is there a way to save Strings after the program closes? - java

I'm trying to make a banking system GUI and I've done well so far but I've run into quite the roadblock. I want to be able to log in, but only if you've previously created an account, but I'm not sure if it's even possible to run my create account class and save the information received for future use since the program will close. I assume it's not possible as I'd need a place to store the username and password for future use, such as a server or something, but I thought I'd ask to see if maybe there was something I could do with an array or something. (P.S. I know I shouldn't use .setLayout(null) but this is just a fun first solo coding project I'm trying to do and I don't understand what people say about it so I'll learn about it later)
Here is my code so far:
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class CreateAccount{
private JPanel panel;
private JFrame frame;
private JLabel username;
private JLabel title;
private JLabel passwordLabel;
private JLabel confirmPasswordLabel;
private JLabel alreadyLoggedIn;
private JTextField usernameText;
private JPasswordField passwordText;
private JPasswordField confirmPasswordText;
private JButton confirmButton;
private JButton alreadyLoggedInButton;
private JLabel failureLabel;
public CreateAccount()
{
panel = new JPanel();
frame = new JFrame();
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.setLayout(null);
Clicklistener click = new Clicklistener();
title = new JLabel("Create New Account");
title.setFont(new Font("Serif", Font.BOLD, 18));
title.setBounds(150,10,200, 25);
panel.add(title);
username = new JLabel("New Username:");
username.setBounds(40,50,100,25);;
username.setFont(new Font("Serif", Font.BOLD, 14));
panel.add(username);
passwordLabel = new JLabel("Create Password:");
passwordLabel.setBounds(30,90,150,25);
passwordLabel.setFont(new Font("Serif", Font.BOLD, 14));
panel.add(passwordLabel);
confirmPasswordLabel = new JLabel("Confirm Password:");
confirmPasswordLabel.setBounds(18,130,150,25);
confirmPasswordLabel.setFont(new Font("Serif", Font.BOLD, 14));
panel.add(confirmPasswordLabel);
alreadyLoggedIn = new JLabel("Already logged in?");
alreadyLoggedIn.setBounds(28,225,200,25);
panel.add(alreadyLoggedIn);
usernameText = new JTextField();
usernameText.setBounds(160,53,225,25);
panel.add(usernameText);
passwordText = new JPasswordField();
passwordText.setBounds(160,93,225,25);
panel.add(passwordText);
confirmPasswordText = new JPasswordField();
confirmPasswordText.setBounds(160,133,225,25);
panel.add(confirmPasswordText);
confirmButton = new JButton("Confirm Login");
confirmButton.setBounds(205,190,125,25);
confirmButton.addActionListener(click);
panel.add(confirmButton);
alreadyLoggedInButton = new JButton("Login Here");
alreadyLoggedInButton.setBounds(140,225, 125,25);
alreadyLoggedInButton.addActionListener(click);
panel.add(alreadyLoggedInButton);
failureLabel = new JLabel("");
failureLabel.setBounds(175,160,400,25);
panel.add(failureLabel);
frame.setVisible(true);
}
public String getUsername() {
return usernameText.getText();
}
public String getPassword() {
return passwordText.getText();
}
private class Clicklistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String password = passwordText.getText();
String confirmedPassword = confirmPasswordText.getText();
if ((password.equals(confirmedPassword)) && (e.getSource() == confirmButton))
{
frame.dispose();
//call Home Page
}
else if(!password.equals(confirmedPassword)) {
failureLabel.setText("Passwords don't match. Try Again!");
}
if (e.getSource() == alreadyLoggedInButton)
{
frame.dispose();
new Login();
}
}
}
}
My Login class code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login {
private JFrame frame;
private JPanel panel;
private JLabel userLabel;
private JTextField userText;
private JLabel passwordLabel;
private JPasswordField passwordText;
private JButton button;
private JLabel success;
public Login(){
panel = new JPanel();
frame = new JFrame();
frame.setSize(350,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("Username:");
userLabel.setBounds(10, 20, 80, 25); // x , y , width , height
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
button = new JButton("Login");
button.setBounds(135,80,80,25);
button.addActionListener(new Clicklistener());
panel.add(button);
success = new JLabel("");
success.setBounds(10,110,300,25);
panel.add(success);
success.setText("");
frame.setVisible(true);
}
private class Clicklistener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if ((e.getSource() == button))
{
frame.dispose();
}
}
}
}

Related

GUI become's small whenever I make it visible

I've been making an app with java swing and JavaFX and didn't run into a problem until now. Whenever I set the guis visibility to true, the GUI becomes very small, when it should be 1150 px wide, 900 px tall. Does anyone get any ideas?
Main Gui code:
import javax.swing.*;
import java.awt.*;
public class mainGui extends JFrame{
public static JFrame mainScreen = new JFrame("Tamo");
public mainGui() {
JPanel topPanel = new JPanel();
mainScreen.setSize(1150, 900);
mainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainScreen.setResizable(false);
mainScreen.setLayout(new BorderLayout());
topPanel.setBackground(new Color(226, 230, 204));
topPanel.setPreferredSize(new Dimension(1150, 100));
mainScreen.add(topPanel, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
mainScreen.setIconImage(icon.getImage());
mainScreen.setVisible(false);
}
public static void main(String[] args) {
new mainGui();
}
}
Class which make's the gui visible:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static me.rockorbonk.tamodienynas.GUI.mainGui.mainScreen;
public class loginGui extends JFrame implements ActionListener {
private static JFrame frame;
private static JLabel userLabel;
private static JLabel passwordLabel;
private static JLabel success;
private static JButton login;
private static JTextField userText;
private static JPasswordField passwordText;
loginGui() {
frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(this);
panel.add(login);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
frame.setIconImage(icon.getImage());
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
String uname = userText.getText();
String pwd = passwordText.getText();
if(uname.equals("rokasbruz") && pwd.equals("Rokas123")) {
success.setText("Sekmingai prisijungėte!");
ActionListener l = evt -> {
userLabel.setVisible(false);
passwordLabel.setVisible(false);
userText.setVisible(false);
passwordText.setVisible(false);
login.setVisible(false);
success.setVisible(false);
frame.setVisible(false);
mainScreen.setVisible(true);
mainScreen.pack();
};
Timer timer = new Timer(2000, l);
timer.setRepeats(false);
timer.start();
}
else{
success.setText("Slapyvardis arba slaptažodis nesutampa!");
}
}
public static void main(String[] args) {
new loginGui();
}
}
Any help would be appreciated!
P.S. I'm using IntelliJ ultimate as the IDE
-Rock
mainScreen is just a JFrame that does not contain anything. Hence when you make it visible, all you see is the title bar. In order to initialize mainScreen you need to call mainGui constructor. Nonetheless, as Andrew Thompson wrote in his comment, your style of coding a Swing application is very unusual. Consider using a dialog as your login window.
Here is your code that displays mainScreen as I believe you intended. I only changed the ActionListener, in class loginGui, that displays mainGui. I added one line which is indicated with the comment ADDED THIS LINE
import javax.swing.ImageIcon;
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.Timer;
import static me.rockorbonk.tamodienynas.GUI.mainGui.mainScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class loginGui extends JFrame implements ActionListener {
private static JFrame frame;
private static JLabel userLabel;
private static JLabel passwordLabel;
private static JLabel success;
private static JButton login;
private static JTextField userText;
private static JPasswordField passwordText;
loginGui() {
frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(this);
panel.add(login);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
frame.setIconImage(icon.getImage());
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
String uname = userText.getText();
String pwd = passwordText.getText();
if (uname.equals("rokasbruz") && pwd.equals("Rokas123")) {
success.setText("Sekmingai prisijungėte!");
ActionListener l = evt -> {
userLabel.setVisible(false);
passwordLabel.setVisible(false);
userText.setVisible(false);
passwordText.setVisible(false);
login.setVisible(false);
success.setVisible(false);
frame.setVisible(false);
new mainGui(); // ADDED THIS LINE
mainScreen.setVisible(true);
mainScreen.pack();
};
Timer timer = new Timer(2000, l);
timer.setRepeats(false);
timer.start();
}
else {
success.setText("Slapyvardis arba slaptažodis nesutampa!");
}
}
public static void main(String[] args) {
new loginGui();
}
}
Here is how it appears (after logging in).

create a login form and change password from hide to visible

I'm trying to create a login form and I have some problems at getting the showPassword checkBox work. When showPassword is selected I want the content of the JPasswordField, passwordField, to be visible and when showPassword is not selected I want it to be "hide". I don't understant why my code doesn't work. I write the code this way because I want to implement it in the future as a Model View Controller. I'd prefer not to change any attribute from private in public if possible. Any ideas why this doesn't work? Thanks!
package project3;
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class LogInWindow extends JFrame {
private Container container = getContentPane();
private JLabel titleLabel = new JLabel("WarehouseApp");
private JLabel userLabel = new JLabel("USERNAME");
private JLabel passwordLabel = new JLabel("PASSWORD");
private JTextField userTextField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JButton loginButton = new JButton("LOGIN");
private JCheckBox showPassword = new JCheckBox("Show Password");
private JLabel logInAsLabel = new JLabel("LOGIN AS");
private JComboBox<String> logInAsComboBox = new JComboBox<String>();
public LogInWindow() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(10, 10, 370, 370);
this.setName("Login Form");
this.setResizable(false);
this.setLocationRelativeTo(null);
container.setLayout(null);
titleLabel.setBounds(80, -10, 200, 100);
userLabel.setBounds(50, 80, 100, 30);
userTextField.setBounds(150, 80, 150, 30);
passwordLabel.setBounds(50, 130, 100, 30);
passwordField.setBounds(150, 130, 150, 30);
logInAsLabel.setBounds(50, 180, 100, 30);
logInAsComboBox.setBounds(150, 180, 150, 30);
showPassword.setBounds(150, 220, 150, 30);
loginButton.setBounds(150, 260, 100, 30);
Font font = new Font("Times New Roman", Font.BOLD, 30);
titleLabel.setFont(font);
logInAsComboBox.addItem("ADMIN");
logInAsComboBox.addItem("CLIENT");
logInAsComboBox.setSelectedIndex(-1);
container.add(titleLabel);
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(logInAsLabel);
container.add(logInAsComboBox);
container.add(showPassword);
container.add(loginButton);
}
public void showPasswordWhenClicked(ActionListener listenForPassword) {
showPassword.addActionListener(listenForPassword);
}
public boolean getPasswordStatus() {
if (showPassword.isSelected()==true)
return true;
return false;
}
public void setPasswordVisible() {
passwordField.setEchoChar((char) 0);
}
public void setPasswordInvisible() {
passwordField.setEchoChar('*');
}
}
package project3;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller {
private LogInWindow theView;
public Controller(LogInWindow theView) {
this.theView = theView;
this.theView.showPasswordWhenClicked(new showPasswordListener());
}
public class showPasswordListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
if (theView.getPasswordStatus()==true) {
theView.setPasswordVisible();
} else {
theView.setPasswordInvisible();
}
}
}
public static void main(String[] args) {
LogInWindow logIn = new LogInWindow();
logIn.setVisible(true);
}
}
Your code does not create an instance of Controller, so that class’s constructor is never called. Therefore, showPasswordWhenClicked is never called.
Try adding this line to your main method:
new Controller(logIn);

Multiple JPanel Java Application Windows

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);
}

Problems with Layout for Login GUI

I am trying to make a simple GUI that has the username and password with the textfields under each one.
Any help would be greatly appreciated!
Here is my code. I cannot figure out how to get everything in it's rightful place.
enter code here
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 400;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Hello");
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel = new JPanel();
panel.setBackground(blue);
panel.add(instruct);
panel.add(username);
panel.add(usertext);
panel.add(password);
panel.add(passtext);
panel.add(login);
add(panel);
}
}
Change the line where you create the panel to
JPanel panel = new JPanel(new GridLayout(2,2));

2 errors java flops converter

I've got 2 errors:
C:\Users\anderson\Documents\FlopstoGFlopsConverter1.java:80: error: cannot find symbol
long flops = Long.parseLong(this.textField1.getText());
^
symbol: variable textField1
C:\Users\anderson\Documents\FlopstoGFlopsConverter1.java:85: error: cannot find symbol
this.textField2.setText(String.valueOf(gFlops));
^
symbol: variable textField2
2 errors
it's just so difficult to learn.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class FlopstoGFlopsConverter1 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
FlopstoGFlopsConverter1() {
setSize(500, 350);
setVisible(true);
JButton button1 = new JButton("Convert!");
button1.addActionListener(this);
JPanel panel = new JPanel();
panel.add(button1);
panel.setLayout(null);
this.add(panel);
button1.setBounds(190, 230, 100, 30);
JLabel label1 = new JLabel("Enter Flops");
panel.add(label1);
this.add(panel);
label1.setBounds(89, 52, 150, 50);
JTextField textArea1 = new JTextField(20);
JPanel p = new JPanel();
panel.add(textArea1);
this.add(panel);
textArea1.setBounds(160, 69, 160, 20);
JTextField textArea2 = new JTextField(20);
panel.add(textArea2);
this.add(panel);
textArea2.setBounds(159, 155, 160, 20);
JLabel label2 = new JLabel("Gigaflops ");
panel.add(label2);
this.add(panel);
label2.setBounds(91, 150, 200, 30);
}
public static void main(String[]args) {
new FlopstoGFlopsConverter1();
}
public void actionPerformed(ActionEvent e) {
System.out.println("");
try {
long flops = Long.parseLong(this.textField1.getText());
double gFlops = flops/1000000000;
this.textField2.setText(String.valueOf(gFlops));
} catch(Exception exception) {
}
}
}
You need to declare textArea1 and textArea2 as instance variables and use those in actionPerformed() method.
Currently, there are no textField1 and textField2 declared, instead textArea1 and textArea2, but even these are in the local scope of the constructor.
JTextField textArea1 = null; // Outside the constructor, inside the class
JTextField textArea2 = null; // Outside the constructor, inside the class
...
...
// Inside actionPerformed method
long flops = Long.parseLong(this.textArea1.getText()); // use textArea1
...
this.textArea2.setText(String.valueOf(gFlops));
As it says you do not have any declaration of textField1 and textField2. Declare them first. If you meant to use textArea1 and textArea2, declare them as instance variables after the class declaration so you can use them. Your class would look like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class FlopstoGFlopsConverter1 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField textArea1;
private JTextField textArea2;
FlopstoGFlopsConverter1() {
setSize(500, 350);
setVisible(true);
JButton button1 = new JButton("Convert!");
button1.addActionListener(this);
JPanel panel = new JPanel();
panel.add(button1);
panel.setLayout(null);
this.add(panel);
button1.setBounds(190, 230, 100, 30);
JLabel label1 = new JLabel("Enter Flops");
panel.add(label1);
this.add(panel);
label1.setBounds(89, 52, 150, 50);
textArea1 = new JTextField(20);
JPanel p = new JPanel();
panel.add(textArea1);
this.add(panel);
textArea1.setBounds(160, 69, 160, 20);
textArea2 = new JTextField(20);
panel.add(textArea2);
this.add(panel);
textArea2.setBounds(159, 155, 160, 20);
JLabel label2 = new JLabel("Gigaflops ");
panel.add(label2);
this.add(panel);
label2.setBounds(91, 150, 200, 30);
}
public static void main(String[]args) {
new FlopstoGFlopsConverter1();
}
public void actionPerformed(ActionEvent e) {
System.out.println("");
try {
long flops = Long.parseLong(this.textArea1.getText());
double gFlops = flops/1000000000;
this.textArea2.setText(String.valueOf(gFlops));
} catch(Exception exception) {
}
}
}

Categories