I want to add continuously data from JTextFields to a Jtable.
When I click add button, the text from the JTextFields have to be inserted in the Jtable.
This code generates only one row when I click the add button.
I want the row to be added to the previous rows inserted.
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel();
table_1.setModel(model);
model.addColumn("Product Name");
model.addColumn("Product Price");
model.addColumn("Quantity");
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String st[] = {name, price, quantity};
model.addRow(st);
}
Do I need to add an EventHandler to my table? Thank you. Please help me with my assignment.
Move this part:
DefaultTableModel model = new DefaultTableModel();
table_1.setModel(model);
model.addColumn("Product Name");
model.addColumn("Product Price");
model.addColumn("Quantity");
to your constructor and define model as an instance member. Don't create table model for each button click. Below part is enough for actionPerformed.
public void actionPerformed(ActionEvent arg0) {
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String st[] = {name, price, quantity};
model.addRow(st);
}
Edit:
If you share your full code, I can tell you where to put the above parts. But for now, below example code can guide you.
public class TableClass {
DefaultTableModel model;
public TableClass() {
model = new DefaultTableModel();
table_1.setModel(model);
model.addColumn("Product Name");
model.addColumn("Product Price");
model.addColumn("Quantity");
JButton addButton = JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String st[] = {name, price, quantity};
model.addRow(st);
}
})
}
}
Related
I'm trying to make a GUI interface using java swing that is able to add users to a text file that I treat as a database. The GUI interface has a JTable which pulls the existing items in the text file and displays it initially. Once I go to add a new item, it gets updated on the text file but not on the JTable. This is mainly because I only call the JTable once the way I set up my code. I'm wondering how I can call the JTable multiple times or make a button for it to call a refresh of the table and display the newly added items alongside the old items.
I want it to be able to either call the refresh of the table in the updateList function or once the viewButton is pressed which triggers an else if statement which can do that in the actionPerformed function.
Here is my code:
class UserManager extends JFrame implements ActionListener {
private JTextField firstNameField, lastNameField, salaryField;
private JButton addButton, removeButton, viewButton, sortButton, getButton;
private JList<Employee> userList;
private ArrayList<Employee> users;
public UserManager() {
setTitle("Employee Manager");
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
firstNameField = new JTextField(20);
lastNameField = new JTextField(20);
salaryField = new JTextField(20);
addButton = new JButton("Add");
addButton.addActionListener(this);
removeButton = new JButton("Remove");
removeButton.addActionListener(this);
viewButton = new JButton("Refresh List"); // POTENTIAL BUTTON TO REFRESH JTABLE?
viewButton.addActionListener(this);
sortButton = new JButton("Sort List");
sortButton.addActionListener(this);
// Pulling data from text file database
ArrayList<ArrayList<String>> databaseData = ReadFile();
users = new ArrayList<Employee>();
// Adding existing databaseData to users
for (int i = 0; i < databaseData.size(); i++) {
Employee user = new Employee(databaseData.get(i).get(0), databaseData.get(i).get(1), Integer.valueOf(databaseData.get(i).get(2)));
users.add(user);
}
userList = new JList<Employee>(users.toArray(new Employee[0]));
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel firstNamePanel = new JPanel();
firstNamePanel.add(new JLabel("First Name:"));
firstNamePanel.add(firstNameField);
JPanel lastNamePanel = new JPanel();
lastNamePanel.add(new JLabel("Last Name:"));
lastNamePanel.add(lastNameField);
JPanel salaryPanel = new JPanel();
salaryPanel.add(new JLabel("Salary:"));
salaryPanel.add(salaryField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
buttonPanel.add(viewButton);
buttonPanel.add(sortButton);
// Converting 2D arraylist to normal 2D array for JTable
String[][] data = databaseData.stream().map(u -> u.toArray(new String[0])).toArray(String[][]::new);
// Initializing column names of JTable
String[] columnNames = { "FName", "LName", "Salary" };
// Initializing the JTable (THIS IS WHAT I NEED TO REFRESH)
JTable j = new JTable(data, columnNames);
j.setBounds(1000, 1000, 900, 900);
// adding it to JScrollPane
JScrollPane table = new JScrollPane(j);
JPanel mainPanel = new JPanel(new GridLayout(5, 3));
mainPanel.add(firstNamePanel);
mainPanel.add(lastNamePanel);
mainPanel.add(salaryPanel);
mainPanel.add(buttonPanel);
mainPanel.add(table);
add(mainPanel);
}
public void actionPerformed(ActionEvent e) {
// "Add" button is clicked
if (e.getSource() == addButton) {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
int salary = 0;
try {
salary = Integer.parseInt(salaryField.getText());
}
catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "Please enter a valid salary", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Error check to see if full name and age is entered
if (!firstName.equals("") && !lastName.equals("")) {
Employee user = new Employee(firstName, lastName, salary);
users.add(user);
updateList();
firstNameField.setText("");
lastNameField.setText("");
salaryField.setText("");
}
else {
JOptionPane.showMessageDialog(this, "Please enter a valid full name", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// POTENTIAL BUTTON THAT REFRESHES JTABLE?
else if (e.getSource() == viewButton) {
}
}
// Updates the list after a CRUD operation is called
private void updateList() {
userList.setListData(users.toArray(new Employee[0]));
try {
FileWriter fw = new FileWriter("db.txt", false);
// BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter pw = new PrintWriter(bw);
// Loop through each student and write to the text file
for (int i = 0; i < users.size(); i++) {
fw.write(toString(users.get(i).getFirstName(), users.get(i).getLastName(), users.get(i).getSalary()));
}
fw.close();
// CALL A REFRESH FOR THE TABLE HERE??
}
catch (IOException io) {
}
}
// Combing multiple string and ints into a string
public String toString(String firstName, String lastName, int salary) {
return firstName + ", " + lastName + ", " + salary + "\n";
}
// Reading database
public static ArrayList<ArrayList<String>> ReadFile() {
try {
// Choose grades.txt file to look at
File myObj = new File("db.txt");
// Create scanner object
Scanner myReader = new Scanner(myObj);
// Create 2d list array to hold all the single list arrays of single information
ArrayList<ArrayList<String>> combinedArr = new ArrayList<ArrayList<String>>();
// While the file reader is still reading lines in the text
while (myReader.hasNextLine()) {
// Read strings of text in txt file
String data = myReader.nextLine();
// Get first and last name from a string
ArrayList<String> temp = GetName(data);
// Add the person and their salary to the combined array that holds everyones
combinedArr.add(temp);
}
// Close file once there are no more lines to read
myReader.close();
return combinedArr;
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Return invalid list string with nothing if error
ArrayList<ArrayList<String>> Invalid = new ArrayList<ArrayList<String>>();
return Invalid;
}
// Parses name in db
public static ArrayList<String> GetName(String data) {
String first = "";
String last = "";
String sal = "";
// System.out.println(data[0])
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == ',') {
// Start from 2 indexes after the first occurance of the comma
for (int j = i+2; j < data.length(); j++) {
if (data.charAt(j) == ',') {
for (int n = j+2; n < data.length(); n++) {
sal += data.charAt(n);
}
break;
}
last += data.charAt(j);
}
break;
}
first += data.charAt(i);
}
// Initializing package array to send all values
ArrayList<String> arr = new ArrayList<String>();
arr.add(first);
arr.add(last);
arr.add(sal);
return arr;
}
public static void main(String[] args) {
UserManager frame = new UserManager();
frame.setVisible(true);
}
}
class Employee {
// Initalizing variables
private String firstName;
private String lastName;
private int salary;
// Assigning variables
public Employee(String firstName, String lastName, int salary) {
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
// return first name
public String getFirstName() {
return firstName;
}
// return last name
public String getLastName() {
return lastName;
}
// return salary
public int getSalary() {
return salary;
}
}
Initializing the JTable (THIS IS WHAT I NEED TO REFRESH)
You don't refresh the table. The data for all Swing components is contained in a "model". You change the data in the model. When changes to the model are made the table is repainted to reflect the change.
So you could either:
create a new DefaultTableModel (which is unnecessary)
update the existing DefaultTableModel, by using the addRow(...) method to update the model every time you write a new item to your file.
Instead of using code like:
JTable j = new JTable(data, columnNames);
You can use:
model = new DefaultTableModel(data, columnNames)
table = new JTable(model)
Now you can access the DefaultTableModel any time you need to by creating an instance variable in your class or by using the table.getModel() method.
Usually lists and tables are updated through their models. They represent the information shown to the user. You can try this.
Create in your class a new field. Use this field when initializing the table in your constructor.
private JTable userTable;
In your update function, try this:
DefaultTableModel model = new DefaultTableModel();
users = // fetch here for your users
for (int i = 0, i < user.length, i++)
model.addRow(users[i]);
}
// finally set new model in your table
userTable.setModel(model);
userTable.doLayout();
first post here.
How to write method which can change values in JTable when app is on running? getValIn() returns me values in english (i used ResourceBundle for that and its work), but if i change the combobox I want have this value in french in JTable.
It's a piece of code.
public void show(){
String[] lang = {"en", "fr"};
List<String> columns = new ArrayList<String>();
Object[][] obj;
JComboBox combobox = new JComboBox(lang);
combobox.setSelectedIndex(0);
combobox.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(combobox.getSelectedItem().toString().equals("en")){
selectedLang ="en";
}else{
selectedLang = "fr";
}
}
});
obj = getValIn(selectedLang);
TableModel tb= new DefaultTableModel(obj, columns.toArray());
JTable table = new JTable(tb);
It's not necessary to be in JCombobox.
Thanks, have a nice day!
I have a project for class due this Wednesday and am having trouble with a few things: I have two if else statements that control the values presented in two different drop down menus. To me, it appears I'm not getting the information of of the previous drop down(there are two drop downs in which affects the values presented in the next).
Here's my code thus far:
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
int number = Integer.parseInt((String) selection);
if(number>2)
{
style=(style2);
}
else
{
style=(style1);
}
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
roomtype_string=(String) room_type.getSelectedItem();
room_type.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Room Style Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection2 = (String) room_type.getSelectedItem();
if(selection2.equals("Cabin"))
{
room_number=(cabin_string);
}
else
{
room_number=(suite_string);
}
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
roomselected = (String) room_list.getSelectedItem();
room_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection3 = (String) room_list.getSelectedItem();
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
dining_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection4 = (String) dining_list.getSelectedItem();
NOTE: I have since rewritten my code, still no dice:
` //Creates subPanel2 with Occupancy, Room Type, Room, and Dining Time request
JPanel subpanel = new JPanel();
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
Occupancy_Listener occupancy = new Occupancy_Listener();
occupancy_list.addActionListener(occupancy);
//updateStyle(occupancy_string[occupancy_list.getSelectedIndex()]);
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
Style_Listener styleListen = new Style_Listener();
room_type.addActionListener(styleListen);
//updateNumber(style[room_type.getSelectedIndex()]);
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
Room_Listener room = new Room_Listener();
room_list.addActionListener(room);
//updateRoom(room_number[room_list.getSelectedIndex()]);
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
Din_Listener dining = new Din_Listener();
dining_list.addActionListener(dining);
//updateDin(dining_string[dining_list.getSelectedIndex()]);
...
...
...
...
...
}
private class Occupancy_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
System.out.println(selection);
System.out.println(style[0]);
System.out.println(room_number[0]);
updateStyle(selection);
}
}
private class Style_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateNumber(selection);
}
}
private class Room_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateRoom(selection);
}
}
private class Din_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateDin(selection);
}
}
protected void updateStyle(String pick)
{
String[] style1 ={"Cabin", "Suite"};
String[] style2 ={"Suite"};
//ocu_string=pick;
number = Integer.parseInt(pick);
if(number>2)
{
style=style2;
}
else
{
style=style1;
}
}
protected void updateNumber(String pick)
{
String[] cabin_string = {"11-1","11-2","11-3","11-4","11-5","11-6","11-7","11-8","11-9","11-10"};
String[] suite_string = {"11-S1","11-S2"};
type=pick;
if(type.equals("cabin"))
{
room_number=cabin_string;
}
else
{
room_number=suite_string;
}
}
protected void updateRoom(String pick)
{
room_num=pick;
}
protected void updateDin(String pick)
{
din_time=pick;
}
//public String getPopulation()
{
//return ocu_string;
}
This might be what your are asking. You select an item from the first combo box and it populates items in a second combo box:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox<String> mainComboBox;
private JComboBox<String> subComboBox;
private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox<String>( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox<String>();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You may be confused by the fact that code inside anonymous classes (or local classes) is not executed at the same time as the code around it.
So in a code that looks like:
A a = new A();
a.setSomething( new B() {
public void bMethod() {
// Run stuff
}
} );
C c = a.getSomething();
The "Run stuff" part is not ran now. An object is created, with a method that can be used later inside it, and that object is passed into a. The method is not going to run until something specifically calls it. When you get to the getSomething(), the "Run stuff" part has not run.
So in your code:
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
You create the occupancy list, you create an action listener for it, and store that action listener inside your occupancy list. But none of the stuff written inside the actionPerformed() method is going to run until the GUI is displayed, the user selects something, and the event is fired.
GUI programming is different than console programming where you call "scan()" and then the program just stops and waits for something to be entered. You first prepare the GUI, and when you display it, the various listeners are called based on what the user does.
So your code jumps straight to the occupancy_list.getSelectedItem() before the list has even been added to the GUI, and of course, nothing is selected, nothing is displayed, yet, so the other drop-down lists are created way before the user even sees the GUI.
This is true for all the action listeners in the code.
The proper way to write an action listener is to think what will be the conditions when the GUI is already running. Your action listeners merely set values in local variables that are going to be discarded. Instead, they should do the things that you want to do when the user makes a selection, right inside the action listener.
This means that the action listener for this combo box will have to create the other lists and add them to the GUI, revalidate and repaint it. Or it may simply modify the other lists which will be created already, depending on what you think is best. But they will have to access those lists, and therefore the lists have to be defined as fields of the surrounding class, and accessed inside the action listener. Note that you can also define a method that does this and call it from inside the action listener.
My suggestion would be to create a simple GUI first with just the first combo box and make it change something simple based on the selection. You can follow the Oracle Tutorial, for example. After you understand how to write an action listener that changes something simple, expand your program to add the other lists and manipulate them from the action listener.
I have a JTable with the column names " Names " , " Quantity " and " Unit " .
I'm coding a program where you get the ingredients names.
So i need to get the whole row of one column and String it all up together,
because i need to store it in mySql and i have already set it all as String.
Any idea how i can do this ?
My code are as follows :
JTable Code:
DefaultTableModel model = (DefaultTableModel)table.getModel();
if(!txtQty.getText().trim().equals("")){
model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()});
}else{
JOptionPane.showMessageDialog(null,"*Quantity field left blank");
}
Getting the values and for storing :
for(int i = 1; i<= i ; i++){
ingredients = table.getName();
}
This is for loop is wrong and it does not work because i have a constructor to take in Ingredients but because it is inside the loop, it cannot take it in.
Any suggestions please ? Thank you.
Constructor :
Food e2 = new Food(Name, Description, priceDbl, Image, Category, Ingredients, promotion );
e2.createFood();
I'm coding a program where you get the ingredients names. So i need to get the whole row of one column and String it all up together, because i need to store it in mySql and i have already set it all as String.
Want to do so, try this. Here I am getting result into ArrayList and String, as I am commented ArrayList you can avoid it.
public class TableValuePrint extends JFrame implements ActionListener{
private final JButton print;
private final JTable table;
private String str="";
public TableValuePrint() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", "Pass"},
{"Jhon", "ewrewr", "Fail"},
{"Max", "zxczxc", "Pass"}
};
table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Result");
setSize(1000,700);
print=new JButton("Print");
JPanel jpi1 = new JPanel();
jpi1.add(print);
tablePanel.add(jpi1,BorderLayout.SOUTH);
print.addActionListener(this);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableValuePrint ex = new TableValuePrint();
ex.setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==print){
// ArrayList list = new ArrayList();
for(int i = 0;i<table.getModel().getRowCount();i++)
{
//list.add(table.getModel().getValueAt(i, 0)); //get the all row values at column index 1
str=str+table.getModel().getValueAt(i,0).toString();
}
//System.out.println("List="+list);
System.out.println("String="+str);
}
}
}
Output
String=MoniJhonMax
I am trying to change values of items in my arraylist. I can't seem to get this working. I am at a loss as to how to really ask this question. The code is quite extensive (or at least it is in my book) so I can't really show all of it. However if I know the current index, how can I make it change the ItemName?
currentIndex.setItemName(newItemName);
CurrentIndex is an int that tells me which index I am at, ItemName is a string that is in my arraylist. Should I be getting the ItemName prior to trying to set it? Something like this
InventoryItem.getItemName();
currentIndex.setItemName(newItemName);
This also does not work.
Edit: I was asked to show more code. Here is the panel that pops up in my action listener
modifyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JTextField xField = new JTextField(15);
JTextField yField = new JTextField(15);
JTextField zField = new JTextField(15);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Item Name:"));
myPanel.add(xField);
myPanel.add(Box.createVerticalStrut(15)); // a spacer
myPanel.add(new JLabel("Number in inventory:"));
myPanel.add(yField);
myPanel.add(Box.createVerticalStrut(15)); // a spacer
myPanel.add(new JLabel("Unit Price:"));
myPanel.add(zField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter data into all boxes", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
String newItemName = String.valueOf(xField);
String text1 = yField.getText();
String newInventoryAmount = String.valueOf(text1);
int newAmount = Integer.parseInt(newInventoryAmount);
String text2 = zField.getText();
String newUnitPrice = String.valueOf(text2);
double newPrice = Double.parseDouble(newUnitPrice);
inventory.get(currentIndex).setItemName(newItemName);
inventory.get(currentIndex).setInStock(newAmount);
inventory.get(currentIndex).setUnitPrice(newPrice);
}
}
}
);
I'm not sure what your ArrayList is name so I'll just call it arrayList.
Try
arrayList.get(currentIndex).setItemName(newItemName);
arrayList.get(currentIndex) calls the element from your list at the current index
That allows you to use .setItemName(newItemName) to change the name of the object.
ìnt doesn't have a method setItemName (or any method at all, since it's a primitive, not an object).
Try yourArrayList.get(currentIndex).setItemName(newItemName);
It calls setItemName on the desired element of the list.
EDIT: to fix your new problem, replace String newItemName = String.valueOf(xField); with
String newItemName = xField.getText();
I believe this is what you want to do.
list.set(index, newItemName)
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#set(int, E)
Check out this code that accomplishes what I think you are trying to do.
public class Test {
public static void main(String args[]){
ArrayList<Employee> myArrayList = new ArrayList<Employee>();
Employee e1 = new Employee();
e1.setName("Juan");
myArrayList.add(e1);
myArrayList.get(0).setName("Jhon");
System.out.println(myArrayList.get(0).getName());
}
}
class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}