Related
Using Java -- Create a HashMap<String, Customer> and display HashMap in a sorted view using JDialog/JList.
Class - Customer:
Fields:
int id
String firstName
String lastName
Constructor:
public Customer(int id, String firstName, String lastName) {
}
Getters/Setters/toString
Class - CustomerLibrary:
Fields:
HashMap<String, Customer>
Create methods to add customers to hashmap, display entire hashmap and display single customer based on id number.
ie. addCustomer(String key, Customer value)
ie. displayLibrary()
ie. displayChoice(String value)
Class - Driver:
Create a method called init() and inside create 3-5 Customer Objects and store them in a HashMap<String, Customer> using the method you created in CustomerLibrary.
ie. Customer Example: Customer c1 = new Customer(001, “Bob”, “Smith”);
Create another method called loadFrame() which opens a JFrame.
Class – MainFrame
Design a JFrame that contains a MenuBar. In the MenuBar create a dropdown menu called ‘File’ with two options inside called ‘Show Customers’ and ‘Exit’. When ‘Show Customers’ is selected a new JDialog should appear where all the Customers in the HashMap are displayed in sorted order based on ID (ie. 001, 002, 003). When ‘Exit’ is selected, exit the program (ie. Sysytem.exit(0)). Don’t worry about buttons yet, but one of them should dispose the JDialog but leaves the JFrame running.
Class – CustomerDialog
Design a JDialog that features a JList to display all the Customer Objects stored in the HashMap. Don’t worry about buttons yet, but one of them should dispose the JDialog but leaves the JFrame running.
I have 2 issues:
1 - I have created all my classes and can see that my HashMap is filled with 5 objects, however, when I try to access the HashMap in my JDialog I can't get it to work.
2 - I am uncertain of the best way to create/call a JList.
Any help would be super appreciated. Thank You!
**
CUSTOMER CLASS**
class Customer {
private String id;
private String firstName;
private String lastName;
public Customer(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
CUSTOMERLIBRARY CLASS
public class CustomerLibrary {
private HashMap<String, Customer> library;
public CustomerLibrary() {
library = new HashMap<String, Customer>();
}
public void addCustomer(String key, Customer customer) {
if(key == null) {
throw new IllegalArgumentException("invalid key.");
}
else if(customer == null) {
throw new IllegalArgumentException("invalid customer.");
}
library.put(key, customer);
}
public void displayLibrary() {
Iterator itr = library.entrySet().iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
public void displayChoice(String prefix) {
for (Entry<String, Customer> entry : library.entrySet()) {
String key = entry.getKey();
Customer value = entry.getValue();
if(key.equals(prefix)) {
System.out.println(value);
}
}
}
}
MAINFRAME/JFRAME
public class MainFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
}
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("File");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("Show Customers");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CustomerDialog dialog = new CustomerDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Exit");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);;
}
});
mnNewMenu.add(mntmNewMenuItem_1);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[]", "[]"));
}
}
CUSTOMERDIALOG/JDIALOG
public class CustomerDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JList list;
private DefaultListModel listModel;
private CustomerLibrary library;
public static void main(String[] args) {
}
public CustomerDialog() {
this.library = library;
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new MigLayout("", "[grow]", "[grow]"));
JScrollPane scrollPane = new JScrollPane();
{
listModel = new DefaultListModel();
list = new JList(listModel);
listModel.addElement(library.toString());
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(list.getSelectedValue());
}
}
});
scrollPane.setViewportView(list);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
public void setCustomers(List<Customer> customers) {
for(Customer customer : customers) {
listModel.addElement(customer);
}
}
}
DRIVER CLASS
public class Driver {
public static CustomerLibrary library;
public static void main(String[] args) {
Driver driver = new Driver();
driver.init();
driver.loadFrame();
}
private void init() {
CustomerLibrary library = new CustomerLibrary();
Customer c1 = new Customer("001", "Joe", "Smith");
Customer c2 = new Customer("002", "Alan", "Shepphard");
Customer c3 = new Customer("004", "Lily", "Issaac");
Customer c4 = new Customer("005", "Jennifer", "Conner");
Customer c5 = new Customer("003", "Jared", "Zartme");
library.addCustomer(c1.getId(), c1);
library.addCustomer(c2.getId(), c2);
library.addCustomer(c3.getId(), c3);
library.addCustomer(c4.getId(), c4);
library.addCustomer(c5.getId(), c5);
//library.displayLibrary();
//library.displayChoice("001");
}
private void loadFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
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());
}
}
So i have two classes, one called ApplicationViewer and one called PetshopOverview. I want the applicationviewer to display some information in two tabs using JTabbedPane. I need to get some information from another class which extends JScrollPane, however, the tab does not display the information. I have look at various answers but it seems that mine does not work. See code below:
public class ApplicationViewer extends JFrame{
public void viewer(final ArrayList<PetShop> petshops){
lookAndFeel(); //this calls the look and feel method which changes the looks of the frame.
PetshopOverview ov = new PetshopOverview(petshops);
Object[] columnNames = {"Name", "Address", "Phone Number", "Website", "Opening Time"}; //declaring columns names
Object[][] rowData = new Object[petshops.size()][columnNames.length]; //initializing rows.
DefaultTableModel listTableModel;
for (int i = 0; i < petshops.size(); i++) { //this for loop adds data from the arraylist to each coloumn.
rowData[i][0] = petshops.get(i).getName();
rowData[i][1] = petshops.get(i).getAddress();
rowData[i][2] = petshops.get(i).getPhoneNumber();
rowData[i][3] = petshops.get(i).getWebsite();
rowData[i][4] = petshops.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
JPanel panelLB = new JPanel();
JPanel panel = new JPanel();
JPanel panelBT = new JPanel();
JButton btnViewSum = new JButton("View Summary");
JButton btnExp = new JButton("Export table data");
//---------------------JTABLE AND JFRAME (adding adding table, panels and buttons to the jframe)--------------------------------------------------------
JTable listTable;
listTable = new JTable(listTableModel);
listTable.setRowSelectionAllowed(true);
JScrollPane scroll = new JScrollPane(listTable);
scroll.setViewportView(listTable);
JFrame frame = new JFrame("PetShops");
JTabbedPane tab = new JTabbedPane();
tab.addTab("Tab1", scroll);
tab.addTab("Tab2", new PetshopOverview(petshops));
JLabel lb = new JLabel("Welcome to Pet shop app");
panelBT.add(lb);
panelBT.add(btnExp);
panelBT.add(btnViewSum);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.add(panelBT);
frame.add(tab);
frame.getContentPane().add(panelBT, java.awt.BorderLayout.NORTH);
frame.getContentPane().add(tab, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
}
This is the other class PetshopOverview:
public class PetshopOverview extends JScrollPane{
public PetshopOverview(ArrayList<PetShop> petshopsSum){
Object[] columnNames = {"Name", "Opening Time"};
Object[][] rowData = new Object[petshopsSum.size()][columnNames.length];
DefaultTableModel listTableModel;
int size= petshopsSum.size();
for (int i = 0; i < size; i++) {
rowData[i][0] = petshopsSum.get(i).getName();
rowData[i][1] = petshopsSum.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
//-------------------------JTABLE AND JFRAME--------------------------
JTable listTable;
listTable = new JTable(listTableModel);
Petshop:
public class PetShop {
private String name, address, phoneNumber, website, openingTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public PetShop(String sName, String sAddress, String sPhoneNumber, String sWebsite, String sOpeningTime){
this.name = sName;
this.address = sAddress;
this.phoneNumber = sPhoneNumber;
this.website = sWebsite;
this.openingTime = sOpeningTime;
}
#Override
public String toString(){
return getName()+"\n"
+getAddress().replaceAll(":", "").replaceFirst("", " ")+"\n"
+getPhoneNumber()+"\n"
+getWebsite().replaceFirst("", " ")+"\n"
+getOpeningTime().replaceFirst(",", "").replaceFirst("", " ")+"\n\n";
}
public PetShop(String sName, String sOpeningTime){
this.name = sName;
this.openingTime = sOpeningTime;
}
public String toString2 (){
return getName()+": "
+getOpeningTime().replaceFirst(",", "").replaceFirst("", " ");
}
}
You're almost there i think you just need to adjust the frame and add your components to it. So in ApplicationViewer instead of creating a new JFrame add your components to ApplicationViewer which is already a JFrame. And on PetShopOverview you need to set the ViewportView of the PetShopOverview to the listTable.
Here's an example :
PetShop
public class PetShop {
String name;
String openingTime;
String address;
String phoneNumber;
String website;
public PetShop(String name, String openingTime, String address, String phoneNumber, String website) {
this.name = name;
this.openingTime = openingTime;
this.address = address;
this.phoneNumber = phoneNumber;
this.website = website;
}
public String getName() {
return name;
}
public String getOpeningTime() {
return openingTime;
}
public String getAddress() {
return address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getWebsite() {
return website;
}}
PetShopOverview:
public class PetShopOverview extends JScrollPane {
public PetShopOverview(ArrayList<PetShop> petshopsSum) {
Object[] columnNames = { "Name", "Opening Time" };
Object[][] rowData = new Object[petshopsSum.size()][columnNames.length];
DefaultTableModel listTableModel;
int size = petshopsSum.size();
for (int i = 0; i < size; i++) {
rowData[i][0] = petshopsSum.get(i).getName();
rowData[i][1] = petshopsSum.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
// -------------------------JTABLE AND JFRAME--------------------------
JTable listTable;
listTable = new JTable(listTableModel);
this.setViewportView(listTable);
}}
ApplicationViewer:
public class ApplicationViewer extends JFrame {
public ApplicationViewer(ArrayList<PetShop> petshops) {
viewer(petshops);
}
public void viewer(final ArrayList<PetShop> petshops) {
PetShopOverview ov = new PetShopOverview(petshops);
Object[] columnNames = { "Name", "Address", "Phone Number", "Website", "Opening Time" }; // declaring columns
// names
Object[][] rowData = new Object[petshops.size()][columnNames.length]; // initializing rows.
DefaultTableModel listTableModel;
for (int i = 0; i < petshops.size(); i++) { // this for loop adds data from the arraylist to each coloumn.
rowData[i][0] = petshops.get(i).getName();
rowData[i][1] = petshops.get(i).getAddress();
rowData[i][2] = petshops.get(i).getPhoneNumber();
rowData[i][3] = petshops.get(i).getWebsite();
rowData[i][4] = petshops.get(i).getOpeningTime();
}
listTableModel = new DefaultTableModel(rowData, columnNames);
JPanel panelLB = new JPanel();
JPanel panel = new JPanel();
JPanel panelBT = new JPanel();
JButton btnViewSum = new JButton("View Summary");
JButton btnExp = new JButton("Export table data");
// ---------------------JTABLE AND JFRAME (adding adding table, panels and buttons to the
// jframe)--------------------------------------------------------
JTable listTable;
listTable = new JTable(listTableModel);
listTable.setRowSelectionAllowed(true);
JScrollPane scroll = new JScrollPane(listTable);
scroll.setViewportView(listTable);
JTabbedPane tab = new JTabbedPane();
tab.addTab("Tab1", scroll);
tab.addTab("Tab2", new PetShopOverview(petshops));
JLabel lb = new JLabel("Welcome to Pet shop app");
panelBT.add(lb);
panelBT.add(btnExp);
panelBT.add(btnViewSum);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.add(panelBT);
this.add(tab);
this.getContentPane().add(panelBT, java.awt.BorderLayout.NORTH);
this.getContentPane().add(tab, java.awt.BorderLayout.CENTER);
this.setVisible(true);
}}
Main method :
public static void main(String[] args) {
ArrayList<PetShop> p = new ArrayList<PetShop>();
p.add(new PetShop("a", "9", "street 1", "123", "www.a.com"));
p.add(new PetShop("b", "10", "street 2", "456", "www.b.com"));
p.add(new PetShop("c", "11", "street 3", "789", "www.c.com"));
p.add(new PetShop("d", "12", "street 4", "000", "www.d.com"));
ApplicationViewer v = new ApplicationViewer(p);
v.setVisible(true);
}
p.s. i just created an arbitrary PetShop 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
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 ?