Displaying the values of an Arraylist with a JTable - java

I created a class named EmployeeGUI that is able to create any amount of user Employee objects and add them to an arraylist. The problem i have is that i have a JTable at the bottom of my GUI that i want to display all the objects that i've created but in my case the GUI Creates a new Table Object each time it goes through a for loop with the details of an object but as the for loop goes on the new details overwrites the old details rather than being added to the bottom of a jtable. Can anyone help me debug my errors?
Here is my Code
import java.awt.event.*;
public class EmployeeGUI extends JFrame implements ActionListener{
/**
* #param args
*/
JFrame frame;
JButton button1, button2, button3, button4;
JTextField box1, box2, box3;
JLabel label1, label2, label3;
JTable table1;
int length = 0;
ArrayList<Employee> empArray = new ArrayList<Employee>();
public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeGUI empG = new EmployeeGUI();
empG.frame.setVisible(true);
}
public EmployeeGUI()
{
initialize();
}
public void initialize() {
// TODO Auto-generated method stub
frame = new JFrame("A Sample Window");
frame.setBounds(50,50,680,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("F-Name:");
label1.setBounds(30,33,54,25);
frame.getContentPane().add(label1);
box1 = new JTextField();
box1.setBounds(94, 35, 128,20);
frame.getContentPane().add(box1);
label2 = new JLabel("S-Name:");
label2.setBounds(250,33,54,25);
frame.getContentPane().add(label2);
box2 = new JTextField();
box2.setBounds(305, 35, 128,20);
frame.getContentPane().add(box2);
label3 = new JLabel("Phone:");
label3.setBounds(461,33,54,25);
frame.getContentPane().add(label3);
box3 = new JTextField();
box3.setBounds(500, 35, 128,20);
frame.getContentPane().add(box3);
button1 = new JButton("Add Employee");
button1.addActionListener(this);
button1.setBounds(71,131,113,39);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Employee");
button2.addActionListener(this);
button2.setBounds(194,131,128,39);
frame.getContentPane().add(button2);
button3 = new JButton("Display Employee");
button3.addActionListener(this);
button3.setBounds(332,131,128,39);
frame.getContentPane().add(button3);
button4 = new JButton("Quit Program");
button4.addActionListener(this);
button4.setBounds(475,131,113,39);
frame.getContentPane().add(button4);
table1 = new JTable();
table1.setBounds(0,184,664,178);
frame.getContentPane().add(table1);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = ((JButton) e.getSource()).getActionCommand();
if(action.equals("Add Employee"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
int mobile = Integer.parseInt(pNo);
Employee ee = new Employee(fName,lName,mobile);
empArray.add(ee);
length++;
JOptionPane.showMessageDialog(null, "Employee Added");
}
if(action.equals("Remove Employee"))
{
String fName = box1.getText(), lName = box2.getText();
int mobile = Integer.parseInt(box3.getText());
Employee ee = new Employee(fName,lName,mobile);
if(length>0)
{
for(int i=0; i<empArray.size(); i++)
{
if(empArray.get(i).getLName() == ee.getLName())
{
empArray.remove(i);
JOptionPane.showMessageDialog(null, "Employee Removed");
}
}
}
else{
throw new ListEmptyException("List is Empty");
}
}
if(action.equals("Display Employee"))
{
for(int i = 0; i <empArray.size(); i++)
{
table1.setModel(new DefaultTableModel(
new Object[][] {
{empArray.get(i).getFName(),empArray.get(i).getLName(),empArray.get(i).getMobile()}
},
new String[] {
"First Name", "Surname", "Phone Number"
}
));
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
and the Employee Class
public class Employee {
private String fName,lName;
private int mobile;
public Employee(String fName, String lName, int mobile)
{
setFName(fName);
setLName(lName);
setMobile(mobile);
}
private void setMobile(int mobile) {
// TODO Auto-generated method stub
this.mobile = mobile;
}
public void setLName(String lName) {
// TODO Auto-generated method stub
this.lName = lName;
}
public void setFName(String fName) {
// TODO Auto-generated method stub
this.fName = fName;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public int getMobile()
{
return mobile;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getMobile();
}
public void print()
{
System.out.println(toString());
}
}

only comment, longer
see number of table1.setModel(new DefaultTableModel( created in loop for(int i = 0; i <empArray.size(); i++)
new Object[][] {{empArray.get(i).getFName(), empArray.get(i).getLName(),empArray.get(i).getMobile()}}, is converted to DataVector, you lost, haven't access to this array
(if is there reason to hold two the same arrays in your program then) use array based on util.List in AbstractTableModel

the new details overwrites the old details rather than being added to the bottom of a jtable.
First add all the record in a List then set the model just once otherwise it will override the last one in loop.
sample code:
if (action.equals("Display Employee")) {
List<Object[]> list = new ArrayList<Object[]>();
for (int i = 0; i < empArray.size(); i++) {
list.add(new Object[] {
empArray.get(i).getFName(),
empArray.get(i).getLName(),
empArray.get(i).getMobile()
});
}
table1.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}

You can use the addRow() method of the DefaultTableModel, like this:
((DefaultTableModel)table1.getModel()).addRow(new Object[] {
empArray.get(i).getFName(),
empArray.get(i).getLName(),
empArray.get(i).getMobile()
});

Related

How to count data in jtable and show on the bottom of my gui

I have such an api. It shows JTable with 3 columns. I want that when I insert price and quantity to the jtable result will be seen on the bottom of my jframe. For example I insert data like on the picture and then get the result (2*5)+(2*5)=20. My result will be 20. And this result will be seen on the bottom of the gui window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener{
private static void createAndShowUI() {
JFrame frame = new JFrame("Customer Main");
frame.getContentPane().add(new FuGui(), BorderLayout.CENTER);
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();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class FuGui extends JPanel {
FuDisplayPanel displayPanel = new FuDisplayPanel();
FuButtonPanel buttonPanel = new FuButtonPanel();
FuInformationPanel informationPanel = new FuInformationPanel();
public FuGui() {
//JTextField textField;
//textField = new JTextField(20);
//textField.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createHorizontalStrut(10));
bottomPanel.add(informationPanel);
setLayout(new BorderLayout());
add(displayPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
buttonPanel.addInfoBtnAddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = informationPanel.getName();
String price = informationPanel.getPrice();
String quantity = informationPanel.getQuantity();
displayPanel.addRow(name, price, quantity);
}
});
}
}
class FuDisplayPanel extends JPanel {
private String[] COLUMNS = {"Name", "Price", "Quantity"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 1);
private JTable table = new JTable(model);
public FuDisplayPanel() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
}
}
class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public FuButtonPanel() {
add(addInfoButton);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
}
class FuInformationPanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JTextField quantityField = new JTextField(10);
public FuInformationPanel() {
add(new JLabel("Kwota:"));
add(nameField);
add(Box.createHorizontalStrut(10));
// add(new JLabel("Price:"));
// add(priceField);
//add(new JLabel("Quantity:"));
// add(quantityField);
}
public String getName() {
return nameField.getText();
}
public String getPrice() {
return priceField.getText();
}
public String getQuantity() {
return quantityField.getText();
}
}
update your addRow method in class FuDisplayPanel to return the total like this and
public int addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
int total = 0;
for (int count = 0; count < model.getRowCount(); count++){
price = model.getValueAt(count, 1).toString();
quantity = model.getValueAt(count, 2).toString();
if(price != null && !price.trim().equals("") && quantity != null && !quantity.trim().equals("")) {
total += Integer.parseInt(price) * Integer.parseInt(quantity);
}
}
return total;
}
public class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public JLabel total = new JLabel("Total : ");
public FuButtonPanel() {
add(addInfoButton);
add(total);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
public void setTotal(int total) {
this.total.setText("Total : " + total);
}
}
and do this at FuGui.class
int total = displayPanel.addRow(name, price, quantity);
buttonPanel.setTotal(total);
Access the underlying data in the table via the model (Swing fundamental):
TableModel model = table.getModel();
Add a listener to the table model to do the automatic updates:
TableModelListener listener = new TableModelListener(tableChanged(TableModelEvent e) {
// update code here
}};
table.getModel().addTableModelListener(listener);

How to add component to JTabbedPane

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

Issues with JList Calculation (CVE)?

I've been trying to get a running total price of all the elements within my Jlist as they are being added however just can't seem to get it to work. I've tried to provide the classes necessary to be able to reproduce my problem for greater clarity on what I'm trying to do. Thank you.
-Main GUI
public class PaymentSystemGUI extends javax.swing.JFrame {
private JLabel priceLabel;
private JLabel totalLabel;
private JTextField totalField;
private JButton scanBtn;
private JList checkoutList;
private JScrollPane jScrollCheckout;
private JLabel jLabel1;
private JButton removeBtn;
private JButton addBtn;
private JTextField priceField;
private JTextField barcodeField;
private JLabel barcodeLabel;
private JTextField itemNameField;
private JLabel jItemName;
private JLabel editorLabel;
private JScrollPane checkScrollPane;
private JScrollPane jScrollPane1;
private JMenuItem exitButton;
private JMenu StartButton;
private JMenuBar MainMenBar;
private DefaultListModel Inventory = new DefaultListModel();
private DefaultListModel checkoutBasket = new DefaultListModel();
private JList productList;
private InventoryList stockInst;
private JFileChooser chooser;
private File saveFile;
private boolean changesMade;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PaymentSystemGUI inst = new PaymentSystemGUI();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public PaymentSystemGUI() {
super();
initGUI();
stockInst = new InventoryList();
productList.setModel(stockInst);
checkoutList.setModel(checkoutBasket);
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(new java.awt.Color(245, 245, 245));
this.setEnabled(true);
{
MainMenBar = new JMenuBar();
setJMenuBar(MainMenBar);
{
StartButton = new JMenu();
MainMenBar.add(StartButton);
StartButton.setText("File");
{
exitButton = new JMenuItem();
StartButton.add(exitButton);
exitButton.setText("Exit");
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
}
);
}
}
{
jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(31, 84, 275, 323);
jScrollPane1.setAlignmentY(0.4f);
{
ListModel stockListModel = new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
productList = new JList();
jScrollPane1.setViewportView(productList);
BorderLayout stockListLayout = new BorderLayout();
productList.setLayout(stockListLayout);
productList.setBounds(25, 92, 269, 330);
productList.setAlignmentX(0.4f);
productList.setModel(stockListModel);
}
}
{
editorLabel = new JLabel();
getContentPane().add(editorLabel);
editorLabel.setText("INVENTORY");
editorLabel.setBounds(121, 56, 88, 16);
}
{
jItemName = new JLabel();
getContentPane().add(jItemName);
jItemName.setText("Item Name");
jItemName.setBounds(31, 432, 61, 16);
}
{
itemNameField = new JTextField();
getContentPane().add(itemNameField);
itemNameField.setBounds(127, 426, 130, 28);
}
{
barcodeLabel = new JLabel();
getContentPane().add(barcodeLabel);
barcodeLabel.setText("Barcode Number");
barcodeLabel.setBounds(27, 476, 94, 16);
}
{
barcodeField = new JTextField();
getContentPane().add(barcodeField);
barcodeField.setBounds(127, 470, 130, 28);
}
{
priceLabel = new JLabel();
getContentPane().add(priceLabel);
priceLabel.setText("Price of Item");
priceLabel.setBounds(33, 521, 68, 16);
}
{
priceField = new JTextField();
getContentPane().add(priceField);
priceField.setBounds(127, 515, 130, 28);
}
{
addBtn = new JButton();
getContentPane().add(addBtn);
addBtn.setText("Add");
addBtn.setBounds(53, 560, 83, 28);
}
addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evta) {
addButtonPressed();
}
});
{
removeBtn = new JButton();
getContentPane().add(removeBtn);
removeBtn.setText("Remove");
removeBtn.setBounds(148, 560, 83, 28);
removeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
removeButtonPressed();
}
});
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("CHECKOUT");
jLabel1.setBounds(480, 79, 68, 16);
}
{
jScrollCheckout = new JScrollPane();
getContentPane().add(jScrollCheckout);
jScrollCheckout.setBounds(395, 107, 248, 323);
{
ListModel checkoutListModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
checkoutList = new JList();
jScrollCheckout.setViewportView(checkoutList);
checkoutList.setModel(checkoutListModel);
}
}
{
scanBtn = new JButton();
getContentPane().add(scanBtn);
scanBtn.setText("Scan Item into Checkout");
scanBtn.setBounds(59, 613, 161, 28);
scanBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
checkoutBasket.addElement(productList.getSelectedValue());
double totalAddedValue = 0.00;
double oldCheckoutValue = 0.00;
//Iterate to get the price of the new items.
for (int i = 1; i < productList.getModel().getSize(); i++) {
InventItem item = (InventItem) productList.getModel().getElementAt(i);
totalAddedValue += Double.parseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
String checkoutField = totalField.getText();
//Check that cartTextField already contains a value.
if(checkoutField != null && !checkoutField.isEmpty())
{
oldCheckoutValue = Double.parseDouble(checkoutField);
}
totalField.setText(String.valueOf(oldCheckoutValue + totalAddedValue));
checkoutBasket.addElement(productList);
}
});
}
{
totalField = new JTextField();
getContentPane().add(totalField);
totalField.setBounds(503, 442, 115, 28);
totalField.setEditable(false);
}
{
totalLabel = new JLabel();
getContentPane().add(totalLabel);
totalLabel.setText("Total Cost of Items");
totalLabel.setBounds(367, 448, 124, 16);
}
pack();
this.setSize(818, 730);
}
} catch (Exception e) {
// add your error handling code here
e.printStackTrace();
}
}
private void loadMenuItemAction() {
try {
FileInputStream in = new FileInputStream("itemdata.dat");
ObjectInputStream oIn = new ObjectInputStream(in);
stockInst = (InventoryList)oIn.readObject();
productList.setModel(stockInst);
oIn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Failed to read file");
System.out.println("Error : " + e);
}
}
private void clearAllTextFields() {
barcodeField.setText("");
itemNameField.setText("");
priceField.setText("");
}
private void removeButtonPressed() {
int selectedIndex = productList.getSelectedIndex();
if (selectedIndex == -1) {
JOptionPane.showMessageDialog(this, "Select An Item to Remove");
} else {
InventItem toGo = (InventItem)stockInst.getElementAt(selectedIndex);
if (JOptionPane.showConfirmDialog(this, "Do you really want to remove the item from the cart ? : " + toGo,
"Delete Confirmation", JOptionPane.YES_NO_OPTION)
== JOptionPane.YES_OPTION) {
stockInst.removeItem(toGo.getID());
clearAllTextFields();
productList.clearSelection();
}
}
}
private void addButtonPressed() {
String newbarcode = barcodeField.getText();
String newitemName = itemNameField.getText();
String newprice = priceField.getText();
if (newbarcode.equals("") || newitemName.equals("") || newprice.equals("")) {
JOptionPane.showMessageDialog(this, "Please Enter Full Details");
} else {
stockInst.addInventItem(newbarcode, newitemName, newprice);
InventItem newBasket = stockInst.findItemByName(newbarcode);
productList.setSelectedValue(newBasket, true);
clearAllTextFields();
}
}
}
-InventoryList
import javax.swing.DefaultListModel;
public class InventoryList extends DefaultListModel {
public InventoryList(){
super();
}
public void addInventItem(String idNo, String itemName, String total){
super.addElement(new InventItem(idNo, itemName, total));
}
public InventItem findItemByName(String name){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public InventItem findItemByBarcode(String id){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getID().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public void removeItem(String id){
InventItem empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
InventoryItem
import java.io.Serializable;
public class InventItem implements Serializable {
private String idnum;
private String itemName;
private String cost;
public InventItem() {
}
public InventItem (String barno, String in, String price) {
idnum = barno;
itemName = in;
cost = price;
}
public String getID(){
return idnum;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return cost;
}
public String toString(){
return idnum + ": " + itemName + ", £ " + cost;
}
}
I'm a beginner and don't quite know how to change my code to add a single element from the list.
Read the List API and you will find methods like:
size()
get(...)
So you create a loop that loops from 0 to the number of elements. Inside the loop you get the element from the List and add it to the model of the checkoutBasket JList.
Here is the basics of an MCVE to get you started. All you need to do is add the code for the actionPerformed() method to copy the selected item(s):
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JList<String> left;
JList<String> right;
JLabel total;
public SSCCE()
{
setLayout( new BorderLayout() );
// change this to store Integer objects
String[] data = { "one", "two", "three", "four", "five", "four", "six", "seven" };
left = new JList<String>(data);
add(new JScrollPane(left), BorderLayout.WEST);
right = new JList<String>( new DefaultListModel<String>() );
add(new JScrollPane(right), BorderLayout.EAST);
JButton button = new JButton( "Copy" );
add(button, BorderLayout.CENTER);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
DefaultListModel<String> model = (DefaultListModel<String>)right.getModel();
List<String> selected = left.getSelectedValuesList();
for (String item: selected)
model.addElement( item );
// add code here to loop through right list and total the Integer items
total.setText("Selected total is ?");
}
});
total = new JLabel("Selected total is 0");
add(total, BorderLayout.SOUTH);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If you have a problem then delete your original code and post the MCVE showing what you have tried based on the information in this answer. Don't create a new posting.
Edit:
My original answer talked about copying the data from the DefaultListModel. However, your code is using the JList.getSelectedValuesList() method to get a List of selected items. Each of these items needs to be copied from the List to the ListModel of the JList. I updated my answer to reflect this part of your code. I even wrote the code to show you how to copy the items from the list.
So now your next step is to calculate the a total of the items in the "right" JLIst (ie, your checkout basked). In order to do this, you need to change the data in the "left" list to be "Integer" Objects. So now when you copy the Integer objects yo9u can then iterate through the JList and calculate a total value. If you have problems, then any code you post should be based on this MVCE and NOT your real program.

Error Writing Object's Attributes to File from GUI java

I have a problem with my GUI code that I just can't get my head around it and it concerns file writing with GUI Frames.
You see with my code below, I can Add, Remove and Display person Objects with a JTable. The problem I have is writing each attribute of each object to a file named "PersonList.txt".
The annoying thing about this is that supposing I manually put values into the file, my code is able to read each line and create person objects with the values from the files. But if I wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
My Code follows.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class GUIstoringObjects extends JFrame implements ActionListener{
private JFrame frame;
private JButton button1, button2, button3, button4, button5, button6;
private JTextField box1, box2, box3;
private JLabel label1, label2, label3;
private JTable table;
private ArrayList<Person> pList = new ArrayList<Person>();
private ArrayList<Object[]> list;
private File f1, f2;
private PrintWriter pWriter;
private Scanner pReader;
public static void main(String[] args) throws FileNotFoundException{
// TODO Auto-generated method stub
GUIstoringObjects gui = new GUIstoringObjects();
gui.frame.setVisible(true);
}
public GUIstoringObjects()
{
initialize();
}
public void initialize()
{
frame = new JFrame("Adding and Saving Person Objects");
frame.setBounds(75,75,813,408);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("First Name:");
label1.setBounds(32,27,60,25);
frame.getContentPane().add(label1);
label2 = new JLabel("Last Name:");
label2.setBounds(264,27,82,25);
frame.getContentPane().add(label2);
label3 = new JLabel("Phone Number:");
label3.setBounds(504,27,89,25);
frame.getContentPane().add(label3);
box1 = new JTextField();
box1.setBounds(102,26,140,27);
frame.getContentPane().add(box1);
box2 = new JTextField();
box2.setBounds(354,26,140,27);
frame.getContentPane().add(box2);
box3 = new JTextField();
box3.setBounds(599,26,140,27);
frame.getContentPane().add(box3);
button1 = new JButton("Add Person");
button1.addActionListener(this);
button1.setBounds(120,76,122,33);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Person");
button2.addActionListener(this);
button2.setBounds(120,121,122,33);
frame.getContentPane().add(button2);
button3 = new JButton("Display Person List");
button3.addActionListener(this);
button3.setBounds(252,76,154,33);
frame.getContentPane().add(button3);
button4 = new JButton("Save Person List");
button4.addActionListener(this);
button4.setBounds(416,76,154,33);
frame.getContentPane().add(button4);
button5 = new JButton("Load Person List");
button5.addActionListener(this);
button5.setBounds(416,121,154,33);
frame.getContentPane().add(button5);
button6 = new JButton("Quit Program");
button6.addActionListener(this);
button6.setBounds(599,76,140,33);
frame.getContentPane().add(button6);
table = new JTable();
table.setBounds(0,176,797,194);
frame.getContentPane().add(table);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = (((JButton) e.getSource()).getActionCommand());
if(action.equals("Add Person"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
Person p = new Person(fName,lName,pNo);
pList.add(p);
JOptionPane.showMessageDialog(null, fName+" has been Added!");
box1.setText("");
box2.setText("");
box3.setText("");
}
if(action.equals("Remove Person"))
{
String nameChecker = box1.getText();
for(int i = 0; i<pList.size(); i++)
{
if(nameChecker.equals(pList.get(i).getFName()))
{
pList.remove(i);
JOptionPane.showMessageDialog(null, nameChecker+" has been deleted!");
}
}
}
if(action.equals("Display Person List"))
{
list = new ArrayList<Object[]>();
for (int i = 0; i < pList.size(); i++) {
list.add(new Object[] {
pList.get(i).getFName(),
pList.get(i).getLName(),
pList.get(i).getPNo()
});
}
table.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}
if(action.equals("Save Person List"))
{
f1 = new File("PersonList.txt");
try {
pWriter = new PrintWriter(f1);
for(Person p: pList)
{
pWriter.println(p.getFName());
pWriter.println(p.getLName());
pWriter.println(p.getPNo());
}
JOptionPane.showMessageDialog(null, "Person List Stored in File 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Load Person List"))
{
f2 = new File("PersonList.txt");
try {
pReader = new Scanner(f2);
while (pReader.hasNext())
{
String fName = pReader.nextLine();
String lName = pReader.nextLine();
String pNo = pReader.nextLine();
Person p = new Person(fName,lName,pNo);
pList.add(p);
}
JOptionPane.showMessageDialog(null, "Person List Loaded from 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
And This is my person object below
public class Person {
private String fName, lName, pNo;
public Person(String fName, String lName, String pNo)
{
setFName(fName);
setLName(lName);
setPNo(pNo);
}
public void setFName(String fName)
{
this.fName = fName;
}
public void setLName(String lName)
{
this.lName = lName;
}
public void setPNo(String pNo)
{
this.pNo = pNo;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public String getPNo()
{
return pNo;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getPNo();
}
public void print()
{
System.out.println(toString());
}
}
As I already said above, for argument sake we had
Bill
Gates
088491038
Cristiano
Ronaldo
0048103874
The Code would be able to read from the file, but once I tried to add more people from the arraylist, it just wouldn't work, can someone help me out?
But if i wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
Whenever you create an object of PrintWriter, it clear the data of the existing file.
pWriter = new PrintWriter(f1);
You should use append mode property of FileWriter to append the data in the existing file.
FileWriter fileWriter = new FileWriter(f1, true);
^--------- Append Mode
pWriter = new PrintWriter(fileWriter, true);
^----------- Auto Flush
You should close to stream after finishing all the read/writer operation. Better use auto flush property of PrintWriter to avoid manually calling flush() method.
Handle the resources carefully using Java 7- The try-with-resources Statement or finally block.

Manipulating a JComboBox

Hello guys would someone please help me with my program? I have a JComboBox and it has several items inside it. What I want to happen is that whenever the user will click a certain item inside the combobox it should display its item quantity. For example, I clicked on PM1 twice it should display 2 in quantity, if i clicked on PM4 five times then it should display 5 in quantity. I have two classes involved in my program the and the codes are below. By the way I also want to display the quantities beside the item displayed in class CopyShowOrder. Any help will be extremely appreciated Thanks in advance and more power!
Codes of CopyShow:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CopyShow{
private static String z = "";
private static String w = "";
private static String x = "";
JComboBox combo;
private static String a = "";
public CopyShow(){
String mgaPagkainTo[] = {"PM1 (Paa/ Spicy Paa with Thigh part)","PM2 (Pecho)","PM3 (Pork Barbeque 4 pcs.)","PM4 (Bangus Sisig)","PM5 (Pork Sisig)","PM6 (Bangus Inihaw)","SM1 (Paa)","SM2 (Pork Barbeque 2 pcs.)","Pancit Bihon","Dinuguan at Puto","Puto","Ensaladang Talong","Softdrinks","Iced Tea","Halo-Halo","Leche Flan","Turon Split"};
JFrame frame = new JFrame("Mang Inasal Ordering System");
JPanel panel = new JPanel();
combo = new JComboBox(mgaPagkainTo);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
combo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String str = (String)combo.getSelectedItem();
a = str;
CopyShowOrder messageOrder1 = new CopyShowOrder();
messageOrder1.ShowOrderPo();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,250);
frame.setVisible(true);
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
boolean ulitinMoPows = true;
boolean tryAgain = true;
System.out.print("\nInput Customer Name: ");
String customerName = inp.nextLine();
w = customerName;
System.out.print("\nInput Cashier Name: ");
String user = inp.nextLine();
z = user;
do{
System.out.print("\nInput either Dine In or Take Out: ");
String dInDOut = inp.nextLine();
x = dInDOut;
if (x.equals("Dine In") || x.equals("Take Out")){
System.out.print("");
ulitinMoPows = false;
}
else{
JOptionPane.showMessageDialog(null, "Try again! Please input Dine In or Take Out only!","Error", JOptionPane.ERROR_MESSAGE);
ulitinMoPows = true;
System.out.print ("\f");
}
}while(ulitinMoPows);
do{
System.out.print("\nInput password: ");
String pass = inp.nextLine();
if(pass.equals("admin")){
CopyShowOrder messageShowMenu = new CopyShowOrder();
messageShowMenu.ShowMo();
tryAgain = false;
}
if(!pass.equals("admin")){
JOptionPane.showMessageDialog(null, "Try again! Invalid password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
tryAgain = true;
System.out.print ("\f");
}
}while(tryAgain);
CopyShow j = new CopyShow();
}
public static String kuhaOrder()
{
return a;
}
public static String kuhaUserName()
{
return z;
}
public static String kuhaCustomerName()
{
return w;
}
public static String kuhaSanKainPagkain()
{
return x;
}
}
Codes of CopyShowOrder:
public class CopyShowOrder {
public void ShowMo(){
String user = CopyShow.kuhaUserName();
System.out.print("\n\n\t\tCashier: " +user);
String dInDOut = CopyShow.kuhaSanKainPagkain();
System.out.print(" "+dInDOut);
String customerName = CopyShow.kuhaCustomerName();
System.out.print("\n\t\tCustomer Name: " +customerName);
}
public void ShowOrderPo() {
String order = CopyShow.kuhaOrder();
System.out.print("\t\t\t\t\n " +order);
}
}
I'm not sure if is that what you want, but here it goes..
You can have an idea..
import java.awt.BorderLayout;
public class StackOverflow extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTable table;
private JComboBox comboBox = new JComboBox();
private JButton button = new JButton("+");
private JButton button_1 = new JButton("-");
private JScrollPane scrollPane = new JScrollPane();
private List<String> list = new ArrayList<String>();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
StackOverflow dialog = new StackOverflow();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public StackOverflow() {
setTitle("StackOverflow");
setBounds(100, 100, 339, 228);
comboBox.setModel(new DefaultComboBoxModel(new String[] {"ITEM 1", "ITEM 2", "ITEM 3", "ITEM 4", "ITEM 5", "ITEM 6"}));
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
scrollPane.setBounds(10, 43, 303, 131);
contentPanel.add(scrollPane);
{
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Item", "Count"
}
));
scrollPane.setViewportView(table);
}
}
//Gets the table model and clear it
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
//Add comboBox items to table
for (int i = 0; i < comboBox.getItemCount(); i++)
model.addRow(new Object[] { comboBox.getItemAt(i) , 0 });
comboBox.setBounds(10, 12, 203, 20);
contentPanel.add(comboBox);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String selectedItem = (String) comboBox.getSelectedItem();
for (int i = 0; i < table.getRowCount(); i++) {
String tableItem = (String) table.getValueAt(i, 0);
int count = (Integer) table.getValueAt(i, 1)+1;
if (selectedItem.equals(tableItem)) {
table.setValueAt(count, i, 1);
}
}
}
});
button.setBounds(223, 11, 41, 23);
contentPanel.add(button);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String selectedItem = (String) comboBox.getSelectedItem();
for (int i = 0; i < table.getRowCount(); i++) {
String tableItem = (String) table.getValueAt(i, 0);
int count = (Integer) table.getValueAt(i, 1)-1;
if (selectedItem.equals(tableItem)) {
table.setValueAt(count, i, 1);
}
}
}
});
button_1.setBounds(272, 11, 41, 23);
contentPanel.add(button_1);
}
}

Categories