How to create class instances based on user input - java

I have 3 instances of a class being created in another class.
Customer kyle = new Customer(true,false,false,"Kyle",1000.00);
Customer andrew = new Customer(false,true,false,"Andrew",0.00);
Customer connor = new Customer(false,false,true,"Connor",5000.00);
Here is the constructor if you need to see it.
public Customer(boolean regular, boolean payAhead, boolean loyal, String userName, double amountOfStorage) {
this.regular = regular;
this.payAhead = payAhead;
this.loyal = loyal;
this.userName = userName;
this.amtOfStore = amountOfStorage;
}
The user will input one of the three usernames through a jTextField. How do I take there input and have it choose what instance of the class will run? currently I have:
if (usernameInputField.getText().equals(kyle.getUserName())
|| usernameInputField.getText().equals(andrew.getUserName())
|| usernameInputField.getText().equals(connor.getUserName())){
}
But I don't know what should go into the if statement.

The user will input one of the three usernames through a jTextField.
How do I take there input and have it choose what instance of the
class will run?
You can store all the Customer objects into a Map (Customer Name as Key and Customer object as Value) and then upon receiving the user input, retrive the respective Customer object from the Map:
Map<String, Customer> map = new HashMap<>();
map.add("Kyle", new Customer(true,false,false,"Kyle",1000.00));
map.add("Andrew", new Customer(false,true,false,"Andrew",0.00));
map.add("Connor", new Customer(false,false,true,"Connor",5000.00));
Now, get the user input and retrieve the Customer object using the key (customer name by entered by user):
String userInput = usernameInputField.getText();
Customer customer = map.get(userInput);

Don't use a Map, an ArrayList or a JTextField, but instead put the Customers into a JComboBox, and have the user select the available Customers directly. This is what I'd do since it would be more idiot proof -- because by using this, it is impossible for the user to make an invalid selection.
DefaultComboBoxModel<Customer> custComboModel = new DefaultComboBoxModel<>();
custComboModel.addElement(new Customer(true,false,false,"Kyle",1000.00));
custComboModel.addElement(new Customer(false,true,false,"Andrew",0.00));
custComboModel.addElement(new Customer(false,false,true,"Connor",5000.00));
JComboBox<Customer> custCombo = new JComboBox<>(custComboModel);
Note that for this to work well, you'd have to either override Customer's toString method and have it return the name field or else give your JComboBox a custom renderer so that it renders the name correctly. The tutorials will help you with this.
e.g.,
import javax.swing.*;
#SuppressWarnings("serial")
public class SelectCustomer extends JPanel {
private DefaultComboBoxModel<SimpleCustomer> custComboModel = new DefaultComboBoxModel<>();
private JComboBox<SimpleCustomer> custCombo = new JComboBox<>(custComboModel);
private JTextField nameField = new JTextField(10);
private JTextField loyalField = new JTextField(10);
private JTextField storageField = new JTextField(10);
public SelectCustomer() {
custComboModel.addElement(new SimpleCustomer("Kyle", true, 1000.00));
custComboModel.addElement(new SimpleCustomer("Andrew", false, 0.00));
custComboModel.addElement(new SimpleCustomer("Connor", false, 5000.00));
custCombo.setSelectedIndex(-1);
custCombo.addActionListener(e -> {
SimpleCustomer cust = (SimpleCustomer) custCombo.getSelectedItem();
nameField.setText(cust.getUserName());
loyalField.setText("" + cust.isLoyal());
storageField.setText(String.format("%.2f", cust.getAmtOfStore()));
});
add(custCombo);
add(new JLabel("Name:"));
add(nameField);
add(new JLabel("Loyal:"));
add(loyalField);
add(new JLabel("Storage:"));
add(storageField);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SelectCustomer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectCustomer());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
public class SimpleCustomer {
private String userName;
private boolean loyal;
private double amtOfStore;
public SimpleCustomer(String userName, boolean loyal, double amtOfStore) {
this.userName = userName;
this.loyal = loyal;
this.amtOfStore = amtOfStore;
}
public String getUserName() {
return userName;
}
public boolean isLoyal() {
return loyal;
}
public double getAmtOfStore() {
return amtOfStore;
}
#Override
public String toString() {
return userName;
}
}

You can create a lookup map for all the customers. You can even extend this to add and remove customers.
String username = textField.getText().toLowerCase();
if (customerMap.containsKey(username)) {
output.setText(customerMap.get(username).toString());
} else {
output.setText("Not found!");
}
Example
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class App implements Runnable {
private static class Customer {
private String userName;
private boolean regular;
private boolean payAhead;
private boolean loyal;
private double amountOfStorage;
public Customer(String userName, boolean regular, boolean payAhead, boolean loyal, double amountOfStorage) {
this.userName = userName;
this.regular = regular;
this.payAhead = payAhead;
this.loyal = loyal;
this.amountOfStorage = amountOfStorage;
}
#Override
public String toString() {
return String.format("{ userName: %s, regular: %s, payAhead: %s, loyal: %s, amountOfStorage: %s }",
userName, regular, payAhead, loyal, amountOfStorage);
}
}
private static class MainPanel extends JPanel {
private static final long serialVersionUID = -1911007418116659180L;
private static Map<String, Customer> customerMap;
static {
customerMap = new HashMap<String, Customer>();
customerMap.put("kyle", new Customer("Kyle", true, false, false, 1000.00));
customerMap.put("andrew", new Customer("Andrew", false, true, false, 0.00));
customerMap.put("connor", new Customer("Connor", false, false, true, 5000.00));
}
public MainPanel() {
super(new GridBagLayout());
JTextField textField = new JTextField("", 16);
JButton button = new JButton("Check");
JTextArea output = new JTextArea(5, 16);
button.addActionListener(new AbstractAction() {
private static final long serialVersionUID = -2374104066752886240L;
#Override
public void actionPerformed(ActionEvent e) {
String username = textField.getText().toLowerCase();
if (customerMap.containsKey(username)) {
output.setText(customerMap.get(username).toString());
} else {
output.setText("Not found!");
}
}
});
output.setLineWrap(true);
addComponent(this, textField, 0, 0, 1, 1);
addComponent(this, button, 1, 0, 1, 1);
addComponent(this, output, 0, 1, 1, 2);
}
}
protected static void addComponent(Container container, JComponent component, int x, int y, int cols, int rows) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = x;
constraints.gridy = y;
constraints.gridwidth = cols;
constraints.gridwidth = rows;
container.add(component, constraints);
}
#Override
public void run() {
JFrame frame = new JFrame();
MainPanel panel = new MainPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new App());
}
}

Related

How do I pass text input from one JTextField to a variable in another class?

I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class.
package acgregistration;
import java.util.*;
/**
*
* #author Frank
*/
public class AcgRegistration {
public static void main(String[] args) {
memberDialogBox memberDialogBox = new memberDialogBox();
}
}
package acgregistration;
/**
*
* #author Frank
*/
class acgMember {
private String name;
private int num;
private String email;
public acgMember(String name, int number, String email) {
this.name = name;
this.num = number;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package acgregistration;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Frank
*/
public class memberDialogBox {
String options[] = {"Student","Faculty/Staff"};
JComboBox choices = new JComboBox(options);
JButton b = new JButton("Confirm");
JLabel l = new JLabel("Select your ACG Status");
public memberDialogBox(){
frame();
}
public void frame(){
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(210,150);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel p = new JPanel();
p.add(choices);
p.add(b);
p.add(l);
f.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = choices.getSelectedItem().toString();
if ("Student".equals(choices.getSelectedItem())){
studentDialogBox student = new studentDialogBox();
//This code gives me an error code saying I should call
//acgMemberModel
}
else{
facultyDialogBox faculty= new facultyDialogBox();
}
f.dispose();
}
});
}
}
package acgregistration;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class studentDialogBox {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;
public studentDialogBox(acgMemberModel model) {
this.model = model;
frame();
}
public void frame() {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(nameField);
panel.add(emailField);
panel.add(numberField);
panel.add(confirmButton);
frame.add(panel);
confirmButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String number = numberField.getText();
String email = emailField.getText();
acgMember member = new acgMember(name,
Integer.valueOf(number), email);
model.addNew(member);
}
});
}
}
class acgMemberModel {
private List<acgMember> members = new ArrayList<>();
public void addNew(acgMember member) {
members.add(member);
}
public List<acgMember> getMembers() {
return Collections.unmodifiableList(members);
}
}
I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another?
Any help would be highly appreciated! Thank you!
Just create new instance of Member every time when you populate fields and push button in result of this action listener will invoked and you will grab all data from text field and pass it to new instance constructor. Every time you create new Member pass it to MemberModel separate class.
P.S. you need to read something about naming convention of java language especially about variables, you made mistake in way to set action listener to a TextField instead of Button because your variable names completely meaningless. I refactor code in way to change all variable names to human readable form and fix mistake in my solution because all that conventions has not been used.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
MemberModel model = new MemberModel();
StudentsToOutputListener outputListener
= new StudentsToOutputListener(model, new FileOutput(new File("path to your default file")));
Window studentDialog = new StudentDialogBox(model);
Window facilityDialog = new FacultyDialogBox();
Window memberDialog = new MemberDialogBox(studentDialog, facilityDialog);
memberDialog.show();
}
}
class Member {
private String name;
private int number;
private String email;
public Member(String name, int number, String email) {
this.name = name;
this.number = number;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Member{" +
"name='" + name + '\'' +
", number=" + number +
", email='" + email + '\'' +
'}';
}
}
interface Window {
void show();
}
interface Output {
void output(List<Member> members);
}
interface Listener {
void update();
}
class MemberDialogBox implements Window {
private JFrame frame = new JFrame();
private JComboBox<Window> choiceComboBox = new JComboBox<>();
private JButton confirmButton = new JButton("Confirm");
private JLabel selectLabel = new JLabel("Select your ACG Status");
public MemberDialogBox(Window... windows) {
for (Window window : windows) {
choiceComboBox.addItem(window);
}
frame();
}
public void show() {
frame.setVisible(true);
}
public void frame() {
frame = new JFrame();
frame.setSize(210, 150);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(choiceComboBox);
panel.add(confirmButton);
panel.add(selectLabel);
frame.add(panel);
confirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Window window = (Window) choiceComboBox.getSelectedItem();
window.show();
frame.dispose();
}
});
}
}
class StudentDialogBox implements Window, Listener, Output {
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private JButton saveButton = new JButton("Save students to file");
private JFrame frame;
private JList<Member> list = new JList<>();
private MemberModel model;
public StudentDialogBox(MemberModel model) {
this.model = model;
model.addListener(this);
frame();
}
public void show() {
frame.setVisible(true);
}
public void output(List<Member> members) {
list.setListData(members.toArray(new Member[]{}));
}
public void update() {
model.outputStudentsTo(this);
}
public void frame() {
frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(nameField);
panel.add(emailField);
panel.add(numberField);
panel.add(confirmButton);
panel.add(list);
panel.add(saveButton);
frame.add(panel);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
File selectedFile = fileChooser.getSelectedFile();
Output output = new FileOutput(selectedFile);
model.outputStudentsTo(output);
}
});
confirmButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String number = numberField.getText();
String email = emailField.getText();
Member member = new Member(name, Integer.valueOf(number), email);
model.addNewStudent(member);
}
});
}
public String toString() {
return "Student";
}
}
class FacultyDialogBox implements Window {
public void show() {
System.out.println("you need to implement FacultyDialogBox " +
"in similar way than StudentDialog box");
}
public String toString() {
return "Faculty/Stuff";
}
}
class MemberModel {
private List<Member> students = new ArrayList<>();
private List<Member> stuff = new ArrayList<>();
private List<Listener> listeners = new ArrayList<>();
public void addListener(Listener listener) {
listeners.add(listener);
}
private void notifyListeners() {
for (Listener listener : listeners) {
listener.update();
}
}
public void addNewStudent(Member member) {
students.add(member);
notifyListeners();
}
public void addNewStuff(Member member) {
stuff.add(member);
notifyListeners();
}
public void outputStudentsTo(Output output) {
output.output(Collections.unmodifiableList(students));
}
public void outputStuffTo(Output output) {
output.output(Collections.unmodifiableList(stuff));
}
}
class FileOutput implements Output {
private final File destination;
public FileOutput(File destination) {
this.destination = destination;
}
public void output(List<Member> members) {
try (BufferedWriter file = new BufferedWriter(new FileWriter(destination))) {
for (Member member : members) {
file.write(member.toString());
file.write("\n");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
class StudentsToOutputListener implements Listener {
private final MemberModel model;
private final Output output;
public StudentsToOutputListener(MemberModel model, Output output) {
this.model = model;
this.output = output;
model.addListener(this);
}
public void update() {
model.outputStudentsTo(output);
}
}
I update answer to you question clarification, i understand what do you want to implement and fix your program, also i refactor this code and make it more in oop style and more readable, but you need to implement by yourself second dialog Facility in similar way than Student dialog box. Also you need to place every class in this source to different *.java file.
You're talking about data binding. I recently posted a demo that shows how to do what you need as an answer to this question: Switching JPanels moves content diagonally
Essentially, the GUI passes information to the model and vice-versa by events, typically Property Change Events but there are lots of options you could choose. The process would look like this:
User enters a value in a field
The field fires a property change event for the property "value" when it looses focus
The GUI (or controller class) listens for the property change event and fires another event, such as a Vetoable Change Event.
The Model (or controller) listens for the Vetoable change and validates the value, saving the "state" in the correct place. If the validation fails, it fires an exception.
The GUI checks for the veto exception and reverts the field if required.
A similar approach can allow the model to send property change requests to the GUI to update the value of fields.
The benefit of using these events is that it keeps the GUI simple, separates the model from the representation and makes it easier to replace/duplicate the GUI with another technology rather easily.
Have you tried making the variables you want to share between classes public static?

Why does inherited methods only work for one class?

I am new to Java and programming in general and also new to Stack overflow. Im taking a course in object orientation and i am stuck at one assignment. Hope i can get some tips or feedback here.
I have written a fictive Banking program and now i am supposed to write an user interface.
The class SubMenuWindow have graphic components to draw a window in whitch i want to show all my Customers names and ID-numbers.
The Classes CustomerSubWindow and CreditAccountSubWindow inherits from SubMenuWindow since i want both of them to display the customers names and ID numbers.
When i create customer objects everthing works as its supossed to in the frame created from CustomerSubWindow, but the Frame created from CreditAccountWindow wont display the names and ID-numbers. Both inherit from the same parentclass, why dont they have the same behaviour?
I have tried to rewrite the code in different ways but the error persists. Can someone see what might be wrong?
I am aware that there are a bunch of formal convention errors (indentation, varabel names etc)
Here are the three classes:
First is the parent class:
public abstract class SubMenuWindow extends JFrame {
protected BankLogic bank = new BankLogic();
private JPanel customersDisplayPanel;
private JLabel customersDisplayLabel;
JTextArea customersDisplayText;
private GridBagLayout gridBag;
private GridBagConstraints customGrid;
private FlowLayout layout;
private JScrollPane scrollBarDisplayText;
private static final int TEXT_LENGTH = 30;
private static final int ROWS = 20;
private static final int COLUMNS = 50;
private static final int FRAME_HEIGHT = 900;
private static final int FRAME_WIDTH = 1600;
public SubMenuWindow(String title) {
super(title);
createComponents();
FlowLayout layout = new FlowLayout();
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setVisible(false);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setLayout(layout);//
this.add(customersDisplayPanel);
}
private void createComponents(){
gridBag = new GridBagLayout();
customGrid = new GridBagConstraints();
customersDisplayPanel = new JPanel(gridBag);
customersDisplayLabel = new JLabel("Within this frame you can find all
the Customers in the bank");
setCustomersDisplayText(new JTextArea(ROWS,COLUMNS));
scrollBarDisplayText = new JScrollPane(getCustomersDisplayText());
customGrid.gridx = 0;
customGrid.gridy = 1;
customersDisplayPanel.add(customersDisplayLabel, customGrid);
customGrid.gridx = 0;
customGrid.gridy = 2;
customersDisplayPanel.add(scrollBarDisplayText,customGrid);
}
public void createBankLogicCustomer(String firstNameString, String
surNameString, String pnumString ){
bank.createCustomer(firstNameString, surNameString, pnumString);
updateCustomersTextArea();
}
public void updateCustomersTextArea(){
customersDisplayText.setText("");
for(String customer : bank.getAllCustomers()){
customersDisplayText.append(customer + "\n");
}
}
public BankLogic getBank(){
return bank;
}
public static int getTextLength() {
return TEXT_LENGTH;
}
public JTextArea getCustomersDisplayText() {
return customersDisplayText;
}
public void setCustomersDisplayText(JTextArea customersDisplayText) {
this.customersDisplayText = customersDisplayText;
}
}
Second class
public class CustomerSubWindow extends SubMenuWindow {
private JPanel nameInputPanel;
private JTextField firstNameTextField;
private JTextField surNameTextField;
private JTextField pNumTextField;
private JLabel firstNameLabel;
private JLabel surNameLabel;
private JLabel pNumLabel;
private JButton finishButton;
private ActionListener createCustomerButtonPressed;
public CustomerSubWindow(String title) {
super(title);
createComponents();
this.add(nameInputPanel);
}
public void createComponents(){
nameInputPanel = new JPanel();
firstNameTextField = new JTextField(super.getTextLength());
surNameTextField= new JTextField(super.getTextLength());
pNumTextField= new JTextField(super.getTextLength());
firstNameLabel= new JLabel("First name: ");
surNameLabel= new JLabel("Surname: ");
pNumLabel= new JLabel("Person number: ");
finishButton = new JButton("Create customer");
createCustomerButtonPressed = new CustomerButtonListener();
finishButton.addActionListener(createCustomerButtonPressed);
nameInputPanel.add(firstNameLabel);
nameInputPanel.add(firstNameTextField);
nameInputPanel.add(surNameLabel);
nameInputPanel.add(surNameTextField);
nameInputPanel.add(pNumLabel);
nameInputPanel.add(pNumTextField);
nameInputPanel.add(finishButton);
}
private class CustomerButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent custButtonPressed){
if (custButtonPressed.getSource()==finishButton){
String firstNameString = firstNameTextField.getText();
String surNameString = surNameTextField.getText();
String pnumString = pNumTextField.getText();
createBankLogicCustomer(firstNameString, surNameString,
pnumString);
updateCustomersTextArea();
}
}
}
}
And finally the third Class
public class CreditAccountSubWindow extends SubMenuWindow {
private JPanel pNoInputPanel;
private JTextField pNoTextField;
private JLabel pNoLabel;
private JButton pNoButton;
private ActionListener createCreditAccountButtonPressed;
public CreditAccountSubWindow(String title)
super(title);
createComponents();
this.add(pNoInputPanel);
}
public void createComponents(){
pNoInputPanel = new JPanel();
pNoTextField = new JTextField(super.getTextLength());
pNoLabel = new JLabel("Input client ID number");
pNoButton = new JButton("Create Account");
createCreditAccountButtonPressed = new CreditAccButtonListener();
pNoButton.addActionListener(createCreditAccountButtonPressed);
pNoInputPanel.add(pNoLabel);
pNoInputPanel.add(pNoTextField);
pNoInputPanel.add(pNoButton);
}
private class CreditAccButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent creditAccButtonPressed){
if (creditAccButtonPressed.getSource()==pNoButton){
String pNo = pNoTextField.getText();
getBank().createCreditAccount(pNo);
System.out.println(getBank().createCreditAccount(pNo));
}
}
}
}

How can I read a String array index from a JComboBox into a JLabel?

I have a ComboBox holding a String[]'s values. I have several other String[]'s holding numbers. I want the user to be able to select a item from the ComboBox(holding my String[] names) and according to which one they pick, I want that index associated with one of my other arrays to be printed out in a JLabel for display. Here's what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class NewBuild extends JFrame
{
private static final int WIDTH = 900;
private static final int HEIGHT = 350;
//Create array constants
private static final String[] WARRIOR = {"7","6","6","5","15","11","5","5","5"};
private static final String[] KNIGHT = {"12","6","7","4","11","8","9","3","6"};
private static final String[] SWORDSMAN = {"4","8","4","6","9","16","6","7","5"};
private static final String[] BANDIT = {"9","7","11","2","9","14","3","1","8"};
private static final String[] CLERIC = {"10","3","8","10","11","5","4","4","12"};
private static final String[] SORCERER = {"5","6","5","12","3","7","8","14","4"};
private static final String[] EXPLORER = {"7","6","9","7","6","6","12","5","5"};
private static final String[] DEPRIVED = {"6","6","6","6","6","6","6","6","6"};
private static final String[] CLASS_NAMES = {" ", "Warrior", "Knight", "SwordsMan", "Bandit", "Cleric", "Sorcerer", "Explorer", "Deprived"};
private int num;
private int count = 0;
private String classes;
Container newBuildWindow = getContentPane();
private JLabel lblBuildName, lblStartingClass, lblDisplayStartingStats;
private JTextField txtBuildName;
private JComboBox cStartingClasses;
public NewBuild()
{
GUI();
}//End of Constructor
public void GUI()
{
this.setSize(WIDTH, HEIGHT);
newBuildWindow.setBackground(Color.DARK_GRAY);
setTitle("New Build");
setLayout(new GridLayout(5,2));
setVisible(true);
// setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel panel1 = new JPanel(new GridLayout());
JPanel panel2 = new JPanel(new GridLayout(2,3));
lblBuildName = new JLabel("Build Name");
lblBuildName.setForeground(Color.YELLOW);
panel1.setBackground(Color.DARK_GRAY);
panel1.add(lblBuildName);
txtBuildName = new JTextField(15);
txtBuildName.setBackground(Color.LIGHT_GRAY);
panel1.add(txtBuildName);
lblStartingClass = new JLabel("Pick a starting class:");
lblStartingClass.setForeground(Color.YELLOW);
lblDisplayStartingStats = new JLabel("Default");
lblDisplayStartingStats.setForeground(Color.YELLOW);
cStartingClasses = new JComboBox(CLASS_NAMES);
cStartingClasses.addItemListener(new itemChangeListener());
panel2.setBackground(Color.DARK_GRAY);
panel2.add(lblStartingClass);
panel2.add(cStartingClasses);
panel2.add(lblDisplayStartingStats);
//add panels to pane
newBuildWindow.add(panel1);
newBuildWindow.add(panel2);
// pack();
}//End of GUI method
class itemChangeListener implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
}
}
}
}//End of class NewBuild
Any help would be very much appreciated...Please don't just post a solution, I want to understand the code not copy it.
First, create a "wrapper" class which can bind the String values to a particular name (before anyone rushes at me says you can use a Map of some kind, you could, but this "carries" the associated information within a neat package)
public class ClassType {
private String description;
private String[] values;
public ClassType(String description, String[] values) {
this.description = description;
this.values = values;
}
public String[] getValues() {
return values;
}
#Override
public String toString() {
return description;
}
}
Build an array of these ClassTypes and give this to the JComboBox
ClassType[] types = new ClassType[]{
new ClassType("Warrior", WARRIOR),
new ClassType("Knight", KNIGHT),
new ClassType("Swordsman", SWORDSMAN),
new ClassType("Bandit", BANDIT),
new ClassType("Cleric", CLERIC),
new ClassType("Socerer", SORCERER),
new ClassType("Explorer", EXPLORER),
new ClassType("Deprived", DEPRIVED)
};
cStartingClasses = new JComboBox(types);
And when the ItemListener is notified, extract the values from the selected item...
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
ClassType classType = (ClassType) ((JComboBox)e.getSource()).getSelectedItem();
if (classType != null) {
String values[] = classType.getValues();
}
}
}
You can get the index and item as:
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
int index = cStartingClasses.getSelectedIndex();
String item = String.valueOf(cStartingClasses.getSelectedItem());
}
}
Here cStartingClasses is JcomboBox.

Getting information from a text field to use it in a text area in other Class

I've got one class that has two text fields in it: "name" and "surname". I need the information that someone typed in there for a text area in another class. So far I managed to write (Person class):
public class Person extends JPanel implements ActionListener {
TextField nameField;
JTextField surnameField;
public String name;
public String surname;
final static int BIG_BORDER = 75;
final static int SMALL_BORDER = 10;
final static int ELEMENTsLENGHT = 320;
final static int VERTICAL_SPACE = 10;
final static int VERTICAL_SPACE_PLUS = 25;
final static int HORIZONTAL_SPACE = 75;
final static int SPACEforELEMENT_LABEL = 50;
final static int SPACEforELEMENT_TEXT = 40;
final static int H_SPACEforBUTTON = 64;
final static int V_SPACEforBUTTON = 26;
public Person() {
init();
}
public void init() {
JLabel nameLabel = new JLabel("Please enter your name:");
JLabel surnameLabel = new JLabel("Please enter your surname:");
nameField = new JTextField();
nameField.addActionListener(this);
surnameField = new JTextField();
surnameField.addActionListener(this);
nextButton = new JButton("NEXT");
nextButton.setActionCommand(next);
nextButton.addActionListener(this);
JPanel panelButton = new JPanel();
panelButton.add(nextButton);
double size[][] = {
{ BIG_BORDER, ELEMENTsLENGHT, HORIZONTAL_SPACE,
H_SPACEforBUTTON, SMALL_BORDER }, // Columns
{ BIG_BORDER, SPACEforELEMENT_LABEL, VERTICAL_SPACE,
SPACEforELEMENT_TEXT, VERTICAL_SPACE_PLUS,
SPACEforELEMENT_LABEL, VERTICAL_SPACE,
SPACEforELEMENT_TEXT, VERTICAL_SPACE_PLUS,
SPACEforELEMENT_LABEL, VERTICAL_SPACE,
V_SPACEforBUTTON, SMALL_BORDER } }; // Rows
setLayout(new TableLayout(size));
add(nameLabel, "1,1,1,1");
add(nameField, "1,3,1,1");
add(surnameLabel, "1,5,1,1");
add(surnameField, "1,7,1,1");
add(nextButton, "3,11,1,1");
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Identification");
frame.getContentPane().add(new Person());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 450);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
name = nameField.getText();
surname = surnameField.getText();
if (e.getActionCommand().equalsIgnoreCase(next)) {
Person.showNextWindow();
}
}
public static void showNextWindow() {
//cardLayout.next(this);
System.out.println("go to the next window");
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The other class now:
public class Greeting extends JPanel implements ActionListener {
Person person = new Person();
String name = person.name;
String surname = person.surname;
public Greeting() {
super(new BorderLayout());
init();
}
public void init() {
nextButton = new JButton("NEXT");
nextButton.setActionCommand(next);
nextButton.addActionListener(this);
//nextButton.setMnemonic('rightArrow');
String q = "How are you today, "+name+" "+surname+"?";
JTextArea textArea = new JTextArea(q);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
add(textArea, BorderLayout.NORTH);
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.LINE_AXIS));
btnPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
btnPanel.add(Box.createHorizontalGlue());
btnPanel.add(nextButton);
btnPanel.setAlignmentX(RIGHT_ALIGNMENT);
add(btnPanel, BorderLayout.SOUTH);
} // end init
public static void showNextWindow() {
//cardLayout.next(this);
System.out.println("go to the next window");
}
public void actionPerformed(ActionEvent e) {
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("How are you");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Greeting());
frame.setSize(550, 450);
frame.setResizable(false);
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
But what I see in the window is: "How are you today, null null?" Any fresh eyes to catch what's wrong? Thanks
You never show us that you've proven that the ActionListener's are called after the text has been entered into the fields and before the String variables are used elsewhere. Regardless, it's a bad design.
I'd give the class with the JTextFields public getter methods, not public variables, and in the getter methods, I'd extract the text currently in the corresponding JTextField. For instance, something like:
private JTextField nameField = new JTextField();
private JTextField surnameField = new JTextField();
public String getName() {
return nameField.getText();
}
public String getSurname() {
return surnameField.getText();
}
//... etc...
For example, here is an SSCCE that demonstrates your problem and a solution:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class InfoFromTextFields {
private static void createAndShowUI() {
JFrame frame = new JFrame("InfoFromTextFields");
frame.getContentPane().add(new MainGui());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class NamePanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField surnameField = new JTextField(10);
public NamePanel() {
add(new JLabel("Name:"));
add(nameField);
add(Box.createHorizontalStrut(15));
add(new JLabel("Surname:"));
add(surnameField);
}
public String getNameText() {
return nameField.getText();
}
public String getSurnameText() {
return surnameField.getText();
}
}
class MainGui extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField surnameField = new JTextField(10);
public MainGui() {
nameField.setEditable(false);
surnameField.setEditable(false);
add(new JLabel("Name:"));
add(nameField);
add(Box.createHorizontalStrut(15));
add(new JLabel("Surname:"));
add(surnameField);
add(Box.createHorizontalStrut(15));
add(new JButton(new AbstractAction("Get Names") {
#Override
public void actionPerformed(ActionEvent arg0) {
NamePanel namePanel = new NamePanel();
int result = JOptionPane.showConfirmDialog(nameField, namePanel,
"Get Names", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
nameField.setText(namePanel.getNameText());
surnameField.setText(namePanel.getSurnameText());
}
}
}));
}
}
As far as I understand it, action will be fired by JTextFields only (?) when the "enter" key is hit. See example here : Java Tutorial
Does it work if you enter text in the textfields AND hit "enter" before starting the other class/frame ?
Then of course a better solution is getters, like Hovercraft already mentioned :
public String getName(){
return nameField.getText();
}
Better use getter methods:
(Person class):
// public String name;
// public String surname;
// ...
public Person()
{
// ...
nameField = new JTextField();
nameField.addActionListener(this);
surnameField = new JTextField();
surnameField.addActionListener(this);
// and in public void actionPerformed(ActionEvent e) {
// name = nameField.getText();
// surname = surnameField.getText();
// ...
}
private String getName(){return nameField.getText();}
private String getSurname(){return surnameField.getText();}
// ...
The other class:
Person person = new Person();
String name = person.getName();
String surname = person.getSurname();
String q = "How are you today, "+name+" "+surname+"?";
JTextArea textArea = new JTextArea(q);
One way would be to create accessors for the values.. So you should have:
String getName()
{
nameField.getText();
}
and
String getName()
{
surnameField.getText();
}
In you other class you just call those methods to return the values..
You should leave your instance variables as private and never make them public (unless you have a very good reason). Read on Encapsulation

How do i add values entered into TextFields in a JPanel to an array?

I would like to add the values of "HouseNumber,StreetName,Town,Postcode" which are the textfields on my JPanel to the "Address" Array, What would be the best way to go about this? Thanks
Main Class
public class Main{
public static void main(String[] args){
JFrame frame = new JFrame("Burgess-Brown-Pearson Homes");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel HouseNumberLabel = new JLabel("House Number");
JTextField HouseNumber = new JTextField("");
JLabel StreetNameLabel = new JLabel("Street Name");
JTextField StreetName = new JTextField("");
JLabel TownLabel = new JLabel("Town");
JTextField Town = new JTextField("");
JLabel PostCodeLabel = new JLabel("PostCode");
JTextField PostCode = new JTextField("");
JLabel BedsLabel = new JLabel("Number of Beds");
JTextField Beds = new JTextField("");
JLabel PriceLabel = new JLabel("Price");
JTextField Price = new JTextField("");
JLabel TypeLabel = new JLabel("Building Type");
JTextField Type = new JTextField("");
JButton Submit = new JButton("Submit");
frame.setSize(500,500);
panel.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
panel.add(HouseNumberLabel);
panel.add(HouseNumber);
panel.add(StreetNameLabel);
panel.add(StreetName);
panel.add(TownLabel);
panel.add(Town);
panel.add(PostCodeLabel);
panel.add(PostCode);
panel.add(BedsLabel);
panel.add(Beds);
panel.add(PriceLabel);
panel.add(Price);
panel.add(TypeLabel);
panel.add(Type);
panel.add(Submit);
frame.pack();
frame.show();
//Create new Person objects
Address p[] = new Address[3];
p[0] = new Address("27","Abbey View","Hexham","NE46 1EQ");
p[1] = new Address("15", "Chirdon Crescent", "Hexham", "NE46 1LE");
p[2] = new Address("6", "Causey Brae", "Hexham", "NE46 1DB");
Details c[] = new Details[3];
c[0] = new Details ("3", "175,000", "Terraced");
c[1] = new Details ("6", "300,000", "Bungalow");
c[2] = new Details ("4", "250,000", "Detached");
//Send some messages to the objects
c[0].setBeds("3 ");
c[1].setBeds("6");
c[2].setBeds("4");
c[0].setPrice("175,000");
c[1].setPrice("300,000");
c[2].setPrice("250,000");
c[0].setType("Terraced");
c[1].setType("Bungalow");
c[2].setType("Detached");
//Set up the association
p[0].ownsDetails(c[0]);
p[1].ownsDetails(c[1]);
p[2].ownsDetails(c[2]);
System.exit(0);
}
}
Address Class
public final class Address{
//Class properties
private String HouseNumber, StreetName, Town, Postcode;
//Allow this person to own a car
private Details owns;
//Constructor
public Address(String aHouseNumber, String aStreetName, String Town, String Postcode)
{
setHouseNumber(aHouseNumber);
setStreetName(aStreetName);
setTown(Town);
setPostcode(Postcode);
}
public Address(){
}
}
//Add a house
public void ownsDetails(Details owns){
this.owns = owns;
}
//Set methods for properties
public void setHouseNumber(String aName){
HouseNumber = aName;
}
public void setStreetName(String aName){
StreetName = aName;
}
public void setTown(String anName){
Town = anName;
}
public void setPostcode (String anName){
Postcode = anName;
}
//Get methods for properties
public String getHouseNumber(){
return HouseNumber;
}
public String setStreetName(){
return StreetName;
}
public String setTown(){
return Town;
}
public String setPostcode(){
return Postcode;
}
** Details Class **
public final class Details{
//Class properties
private String Type, Beds, Price;
//Constructor
public Details(String aType, String aBeds, String aPrice){
setType(aType);
setBeds(aBeds);
setPrice(aPrice);
}
//Set methods for properties
public void setType(String aType){
Type = aType;
}
public void setBeds(String aBeds){
Beds = aBeds;
}
public void setPrice(String aPrice){
Price = aPrice;
}
//Get methods for properties
public String getType(){
return Type;
}
public String getBeds() {
return Beds;
}
public String getPrice(){
return Price;
}
}
I really don't understand the problem. You have all the methods that you need.
I'll try to give you some tips anyway.
First of all, if the JTextField are used to create new address, and not updating one of the existing, then a static array may not be the right choice. You should use ArrayList instead:
ArrayList<Address> p = new ArrayList<Address>();
Then simply retrieve the data from the JTextFields and construct another Address object:
Address newAddress = new Address(HouseNumber.getText(),
StreetName.getText(),
Town.getText(),
Postcode.getText());
p.add(newAddress);
Is this enough to solve your doubts ?

Categories