Working on a side project for a professor that wants a random number generator.
The program in its current state leaves a lot to be desired but I think I'm on the right track. However, I am stuck when it comes to using the text field, passing that data to my random number equation, and displaying it. Basically, the program isn't waiting for the user input to the text field.
We never made it past OOP in school so I need to pull out the big guns (you guys).
Here is what I am working with currently. The last bit at the end is the part that I am having issue with.
package RandomButton;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
public class GUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField ClassSize;
private JLabel label;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
int x;
int max;
String strMax;
String strX;
Scanner kb = new Scanner(System.in);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Text field code
textField = new JTextField();
textField.setText("1");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setBounds(10, 143, 414, 35);
contentPane.add(textField);
textField.setColumns(10);
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
//Label code
label = new JLabel();
label.setFont(new Font("Tahoma", Font.PLAIN, 70));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 11, 414, 103);
contentPane.add(label);
//math code
Random num = new Random();
strMax = textField.getText();
max = Integer.parseInt(strMax);
x = num.nextInt(max) + 1;
strX = String.valueOf(x);
label.setText(strX);
}
}
What you need is to add an ActionListener, see javadoc here
Simple modification of the code, without bigger discussion, is to move up the code that simulate random numbers...
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
// the listener
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random num = new Random();
String strMax = textField.getText();
int max = Integer.parseInt(strMax);
int x = num.nextInt(max) + 1;
String strX = String.valueOf(x);
label.setText(strX);
}
} );
Related
I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
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.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}
Please be gentle, this is my first time working with Swing and GUI's.
My problem/question:
I have written some code using Java Swing GUI. The validation portion of my code will only recognize if the textField is incorrectly filled out and ignores if the comboBoxes are left empty. Can anyone tell me what I am doing wrong here? My goal is to make sure that all fields are filled out when the user hits submit. Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FeliciasStore_GUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FeliciasStore_GUI frame = new FeliciasStore_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FeliciasStore_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 558, 364);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Size:");
lblNewLabel.setBounds(67, 39, 23, 14);
contentPane.add(lblNewLabel);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setBounds(96, 36, 161, 20);
contentPane.add(comboBox);
comboBox.addItem("Small");
comboBox.addItem("Medium");
comboBox.addItem("Large");
comboBox.addItem("XLarge");
comboBox.setSelectedItem(null);
JLabel lblColor = new JLabel("Color:");
lblColor.setBounds(61, 90, 29, 14);
contentPane.add(lblColor);
JComboBox<String> comboBox_1 = new JComboBox<String>();
comboBox_1.setBounds(96, 87, 161, 20);
contentPane.add(comboBox_1);
comboBox_1.addItem("Blue");
comboBox_1.addItem("Red");
comboBox_1.addItem("Silver");
comboBox_1.addItem("Gold");
comboBox_1.addItem("Aqua");
comboBox_1.addItem("Green");
comboBox_1.addItem("Pink");
comboBox_1.addItem("Purple");
comboBox_1.addItem("White");
comboBox_1.addItem("Black");
comboBox_1.addItem("Orange");
comboBox_1.addItem("Maroon");
comboBox_1.setSelectedItem(null);
JLabel label = new JLabel("");
label.setBounds(518, 122, 19, 0);
contentPane.add(label);
JLabel lblStyle = new JLabel("Style:");
lblStyle.setBounds(62, 141, 28, 14);
contentPane.add(lblStyle);
JComboBox<String> comboBox_2 = new JComboBox<String>();
comboBox_2.setBounds(96, 138, 161, 20);
contentPane.add(comboBox_2);
comboBox_2.addItem("Queen");
comboBox_2.addItem("King");
comboBox_2.addItem("Pawn");
comboBox_2.addItem("Knight");
comboBox_2.addItem("Joker");
comboBox_2.addItem("Babydoll");
comboBox_2.addItem("Superstar");
comboBox_2.setSelectedItem(null);
JLabel lblInscription = new JLabel("Inscription:");
lblInscription.setBounds(36, 192, 54, 14);
contentPane.add(lblInscription);
textField = new JTextField();
textField.setBounds(96, 189, 161, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSubmit_1 = new JButton("SUBMIT");
btnSubmit_1.setBounds(96, 240, 161, 23);
btnSubmit_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textField.getText().length()>15 || comboBox == null || comboBox_1 == null || comboBox_2 == null) {
JOptionPane.showMessageDialog(null, "Insufficient input.", "Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
String enscription = textField.getText();
}
});
contentPane.add(btnSubmit_1);
}
}
Hello I am working on this project to store student names and record their grades. I have the entire program mapped out and all I need to do now is record the integers and strings from the user input and call it from different classes. I am having trouble with this. Do I use an array? How do I call from another class? Thank you.
package gradebook;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class Student extends JFrame {
private JFrame studentFrame;
private JPanel contentPane;
private JTextField studentNameTextField;
protected Component frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Student frame = new Student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
lblPleaseEnterThe.setBounds(130, 105, 194, 16);
contentPane.add(lblPleaseEnterThe);
studentNameTextField = new JTextField("Enter here");
String stdname = studentNameTextField.getText();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student.this.dispose();
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
if(cancelButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
contentPane.setVisible(false);
contentPane.disable();
}
}
});
cancelButton.setBounds(207, 243, 117, 29);
contentPane.add(cancelButton);
}
private void initizalize() {
// TODO Auto-generated method stub
}
}
Is it something along the lines of this?
studentNameTextField = new JTextField("Enter here");
String stdname = studentNameTextField.getText();
I know this would be storing it but how do I call that in a different class so I can make it appear on a different Frame?
Update: Okay so I've done this
Student frame = new Student();
String stdname = frame.studentNameTextField.getText();
JLabel addgradesLabel = new JLabel("Add grades for" + frame.studentNameTextField);
addgradesLabel.setBounds(139, 34, 167, 29);
contentPane.add(addgradesLabel);
And it's still not working. I believe I'm not implementing this correctly. I'm trying to title the label with what the user inputs for the name. So it would but "Add grades for" + stdname But it's not calling it correctly. How can I fix this?
Here is my code from the AddStudentName class
studentNameTextField = new JTextField();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student.this.dispose();
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
What should I add here to save the input that the user is inputting into the JTextField? Thanks for the help
Here's the full code for the classes:
package gradebook;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class Student extends JFrame {
private JFrame studentFrame;
private JPanel contentPane;
public JTextField studentNameTextField;
protected Component frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Student frame = new Student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
lblPleaseEnterThe.setBounds(130, 105, 194, 16);
contentPane.add(lblPleaseEnterThe);
JTextField studentNameTextField = new JTextField();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
if(cancelButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
contentPane.setVisible(false);
contentPane.disable();
}
}
});
cancelButton.setBounds(207, 243, 117, 29);
contentPane.add(cancelButton);
}
private void initizalize() {
// TODO Auto-generated method stub
}
}
and:
package gradebook;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddGrades extends JFrame {
private JPanel contentPane;
private JTextField Assignment1;
private JTextField Assignment2;
private JTextField Assignment3;
private JTextField Assignment4;
private JLabel testsLabel;
private JTextField Test1;
private JTextField Test2;
public JTextField Test3;
public JTextField Test4;
/**
* Launch the application.
*/
public JFrame frame;
public JButton continueButton;
public JButton exitButton;
public static void main(String[] args) {
AddGrades frame = new AddGrades();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddGrades frame = new AddGrades();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddGrades() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
addgradesLabel.setBounds(139, 34, 167, 29);
contentPane.add(addgradesLabel);
JLabel assignmentsLabel = new JLabel("Assignments:");
assignmentsLabel.setBounds(19, 75, 86, 16);
contentPane.add(assignmentsLabel);
Assignment1 = new JTextField();
Assignment1.setBounds(54, 91, 130, 26);
contentPane.add(Assignment1);
Assignment1.setColumns(10);
Assignment2 = new JTextField();
Assignment2.setBounds(54, 129, 130, 26);
contentPane.add(Assignment2);
Assignment2.setColumns(10);
Assignment3 = new JTextField();
Assignment3.setBounds(54, 167, 130, 26);
contentPane.add(Assignment3);
Assignment3.setColumns(10);
Assignment4 = new JTextField();
Assignment4.setBounds(54, 205, 130, 26);
contentPane.add(Assignment4);
Assignment4.setColumns(10);
testsLabel = new JLabel("Tests:");
testsLabel.setBounds(243, 75, 38, 16);
contentPane.add(testsLabel);
Test1 = new JTextField();
Test1.setBounds(262, 91, 130, 26);
contentPane.add(Test1);
Test1.setColumns(10);
Test2 = new JTextField();
Test2.setBounds(262, 129, 130, 26);
contentPane.add(Test2);
Test2.setColumns(10);
Test3 = new JTextField();
Test3.setBounds(262, 167, 130, 26);
contentPane.add(Test3);
Test3.setColumns(10);
Test4 = new JTextField();
Test4.setBounds(262, 205, 130, 26);
contentPane.add(Test4);
Test4.setColumns(10);
continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
if (continueButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
exitButton = new JButton("Exit");
exitButton.setBounds(208, 243, 117, 29);
contentPane.add(exitButton);
}
}
I'm trying to take the input from the JTextField
JTextField studentNameTextField = new JTextField();
and set it on the label
JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
Where stdname would be the user input from the JTextField.
Now I'm getting errors from
public static void main(String[] args) {
AddGrades frame = new AddGrades();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddGrades frame = new AddGrades();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
AddGrades frame = new AddGrades(); gives me error Add argument to match AddGrades(String)
The constructor AddGrades() is undefined
Edit: The best way to do this is to pass an argument to your newly created AddGrades class. See below:
public AddGrades(String stdname) {
JLabel addgradesLabel = new JLabel("Add grades for " + stdname);
}
You will need to modify your code to pass a string to your AddGrades class wherever you create it:
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades(studentNameTextField.getText());
addGradesScreen.setVisible(true);
}
}
});
That worked for me - I downloaded your code and tested it.
JSpinner or JFormattedTextField would be my first thought, but if you can't do that then you could use Integer.parseInt to parse a String to int and a NumberFormat to format the numbers to Strings
Maybe have a look at How to Use Spinners and How to Use Formatted Text Fields for starters
I know this would be storing it but how do I call that in a different class so I can make it appear on a different JFrame?
That's a open question with little context. You might use some kind of "model" which represented one or more Student values; you might use a Observer Pattern to allow the editor to generate events to interested parties which would tell them that something has changed; you might use a Model-View-Controller; you might use a modal dialog and when it's closed, ask the editor for the values via getters.
Have a look at How to Make Dialogs for more details
One of things you want to keep in mind is "responsibility" and "encapsulation". You don't want outside parties to have uncontrolled access into your editor or model, this could allow them to modify the state in an uncontrolled way leading to inconsistencies in your data or UI.
You need to decide who is actually responsible for modifying the state of the model. There's no "right" answer, for example, you could have the editor either be capable of editing existing student objects or creating new ones based on how it's configured, equally, you could also have the editor be "dumb" and simply use setters to setup the editor and getters to get the values.
There are lots of options available to you, which you would use would be based on the context in which you want to use it. My gut feeling is start with an observer pattern and a modal dialog.
So, I have been trying to figure this out for a little bit and cannot figure out how to do it. I want one of my buttons in another class to change the text of a JLabel in the GUI class.
Here is the code from GUI class:`import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GUI extends JFrame{
Container pane = getContentPane();
JButton guess = new JButton("Guess");
JButton gen = new JButton("Generate number");
JTextField userInput = new JTextField();
JLabel Numbers = new JLabel("Press generate to start.");
JLabel guessedNum = new JLabel("");
JLabel error = new JLabel("");
public void CreateGUI(){
final int WIDTH = 325;
final int HEIGHT = 200;
final int centerWIDTH = WIDTH / 4;
final int centerHEIGHT = HEIGHT / 4;
guessHandler guessHandle;
genHandler genHandle;
pane.setLayout(null);
guessHandle = new guessHandler();
guess.addActionListener(guessHandle);
genHandle = new genHandler();
gen.addActionListener(genHandle);
userInput.setBounds(centerWIDTH - 20, centerHEIGHT, 200, 20);
guess.setBounds(userInput.getX() - 35, (userInput.getY() + 25), 105, 50);
gen.setBounds((guess.getX() + 105), guess.getY(), 165, 50);
error.setBounds(70, 125, 300, 20);
Numbers.setBounds(90, 0, 300, 20);
guessedNum.setBounds(20, 25, 300, 20);
pane.add(userInput);
pane.add(guess);
pane.add(gen);
pane.add(Numbers);
pane.add(guessedNum);
pane.add(error);
setSize(WIDTH,HEIGHT);
setTitle("Number Guesser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLocation(350, 150);
}
}
And here the code from the button trying to change the JLabel "error":
`
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class guessHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
GUI gui = new GUI();
gui.changePOS(4, 50, 0, 300, 20);
gui.error.setText("HI from guessHandler.java");
}
}
First, add a getter with public access so your second class can access the field. Something like,
public JLabel getError() {
return error;
}
Or (as #MadProgrammer suggested in the comments, a mutator) like
public void setError(String txt) {
error.setText(txt);
}
Then modify your second class, and pass the instance of GUI to it in the constructor. Like,
public class guessHandler implements ActionListener{
private GUI gui;
public guessHandler(GUI gui) {
this.gui = gui;
}
public void actionPerformed(ActionEvent e) {
gui.changePOS(4, 50, 0, 300, 20);
gui.setError("HI from guessHandler.java");
}
}
I've started working on an extension of a project I've been working on for a few months, and I've felt the need to take it out of the console and put in in a GUI window. So far everything's going great! Except one thing, When I try to test the Login button (It's just so I can limit who uses it, and to see if I could do it.) the action listener isn't responding like I hoped it would. Here's the code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JLayeredPane;
public class Main {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setForeground(Color.GREEN);
frame.setBounds(100, 100, 612, 389);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblUserName = new JLabel("User name");
lblUserName.setBackground(Color.YELLOW);
lblUserName.setBounds(158, 70, 67, 25);
frame.getContentPane().add(lblUserName);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(158, 146, 53, 14);
frame.getContentPane().add(lblPassword);
textField = new JTextField();
textField.setBounds(235, 143, 118, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(235, 72, 118, 20);
frame.getContentPane().add(textField_1);
JButton btnLogin = new JButton("Login");
btnLogin.setBounds(151, 228, 256, 61);
frame.getContentPane().add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(textField.equals("Admin"))
{
if(textField.equals("Admin"))
{
JLabel lblLoginSuccessPlease = new JLabel("LOGIN SUCCESS! Please wait while the other functions are loaded");
lblLoginSuccessPlease.setBounds(124, 204, 344, 14);
frame.getContentPane().add(lblLoginSuccessPlease);
}
}
}
});
JLabel lblWelcomeToMy = new JLabel("Welcome to my amazing program!");
lblWelcomeToMy.setBounds(174, 11, 242, 14);
frame.getContentPane().add(lblWelcomeToMy);
}
}
I've tried to use the && to test both the Username and the Password box, and it wouldn't work either. Also, if someone could instruct me on how to make the Password box have the characters masked that'd be extremely helpful.
if(textField.equals("Admin"))
{
if(textField.equals("Admin"))
{
JLabel lblLoginSuccessPlease = new JLabel("LOGIN SUCCESS! Please wait while the other functions are loaded");
lblLoginSuccessPlease.setBounds(124, 204, 344, 14);
frame.getContentPane().add(lblLoginSuccessPlease);
}
}
First of all, no need to check if textField is equal to "Admin" twice.
But the main problem is that a text field, which is a white rectangle accepting input in a UI, is ever equal to a String, which is a sequence of characters.
What you want to test is if the text entered in the text field is equal to "Admin":
if (textField.getText().equals("Admin"))
Your code has other problems:
using absolute coordinates instead of using a layout manager
adding elements to the frame dynamically instead of adding them from the start and simply making them visible when needed. Adding is needed, but then the GUI needs to be revalidated.
The frame has private access in Main class
private JFrame frame;
change it to public or remove the modifier
To get the text of JTextfield use textfield.getText()
//if (textField.equals("Admin")) {wrong
if (textField.getText().equals("Admin")) {//right way
You have to check the password not the username again
if (textField_1.getText().equals("Admin")) {
f (textField.getText().equals("Admin")) {//this is the password field
To mask the passwords you have to use JPasswordField.so create like
private JPasswordField textField;
and initialize like
textField = new JPasswordField();
and check like
if (textField_1.getText().equals("Admin")) {
if (String.valueOf(textField.getPassword()).equals("Admin")) {
JLabel lblLoginSuccessPlease = new JLabel("LOGIN SUCCESS! Please wait while the other functions are loaded");
lblLoginSuccessPlease.setBounds(124, 204, 344, 14);
frame.getContentPane().add(lblLoginSuccessPlease);
}
}