Tell me, please, what could be the error, in the form on "View the list of products" it does not display a value, although it should display an array of parameters with products. The error in the IDE when creating the button is this: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot call "java.util.ArrayList.iterator()" because "stocks" is null. But in the file for the first information, but not displayed Help is needed!!!!
Stock class file code for storing product parameters
package com.company;
import java.io.Serializable;
class Stock implements Serializable {
private int warehouseNumber;
private String productName;
private double price;
private int count;
private String availability;
public Stock(int warehouseNumber, String productName, double price, int count, String availability) {
this.warehouseNumber = warehouseNumber;
this.productName = productName;
this.price = price;
this.count = count;
this.availability = availability;
}
public void setWarehouseNumber(int warehouseNumber) {
this.warehouseNumber = warehouseNumber;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setPrice(double price) {
this.price = price;
}
public void setCount(int count) {
this.count = count;
}
public void setAvailability(String availability) {
this.availability = availability;
}
public int getWarehouseNumber() {
return warehouseNumber;
}
public String getProductName() {
return productName;
}
public double getPrice() {
return price;
}
public int getCount() {
return count;
}
public String getAvailability() {
return availability;
}
#Override
public String toString() {
return "Warehouse number: " + this.warehouseNumber + ". Product name: " + this.productName + ". Price: " + this.price + ". Count: " + this.count + ". Availability of goods in stock" + this.availability;
}
}
Main file code:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Formatter;
public class Main extends Frame {
public static void main(String[] args) {
Frame mainWindow = new Main();
mainWindow.setTitle("Variant #1, Dudchenko Yaroslav, Group IT92-0/2");
mainWindow.setVisible(true);
mainWindow.setLayout(null);
mainWindow.setResizable(false);
mainWindow.setSize(1000, 600);
mainWindow.setLocation(400, 200);
Frame addFrame = new addGoodsWindow();
Frame deleteFrame = new deleteGoodsWindow();
Frame changeFrame = new changeGoodsWindow();
Button changeGoods = new Button("Change");
changeGoods.setBounds(150, 40, 140, 50);
mainWindow.add(changeGoods);
changeGoods.addActionListener(arg0 -> changeFrame.setVisible(true));
Button deleteGoods = new Button("Delete");
deleteGoods.setBounds(290, 40, 140, 50);
mainWindow.add(deleteGoods);
deleteGoods.addActionListener(arg0 -> deleteFrame.setVisible(true));
Button addGood = new Button("Add");
addGood.setBounds(10, 40, 140, 50);
mainWindow.add(addGood);
TextArea outputWindow = new TextArea();
outputWindow.setBounds(10, 90, 980, 500);
mainWindow.add(outputWindow);
outputWindow.setEditable(false);
addGood.addActionListener(arg0 -> addFrame.setVisible(true));
Button showGoods = new Button("View product list");
showGoods.setBounds(430, 40, 140, 50);
mainWindow.add(showGoods);
showGoods.addMouseListener(new MouseAdapter() {
Dialog dialog;
// Вывод списка продуктов
#Override
public void mouseClicked(MouseEvent e) {
ArrayList<Stock> stocks = null;
try {
stocks = readFromFile();
} catch (IOException ioException) {
System.out.println(ioException);
}
outputWindow.append("Product list:\n");
int i = 1;
for (Stock Stock :
stocks) {
outputWindow.append(i + ". " + Stock.toString() + "\n");
i++;
}
}
//Считывание с файла
public ArrayList<Stock> readFromFile() throws IOException {
Dialog dialog;
ArrayList<Stock> stocks = new ArrayList<>();
try {
FileInputStream fileInputStream = new FileInputStream("database.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Stock object;
try {
while ((object = (Stock) objectInputStream.readObject()) != null) {
stocks.add(object);
}
} catch (EOFException | ClassNotFoundException e) {
}
fileInputStream.close();
objectInputStream.close();
return stocks;
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(mainWindow, "File not found");
}
return stocks;
}
});
// Очистка екрана
Button clearTextarea = new Button("Clear window");
clearTextarea.setBounds(870, 40, 120, 50);
mainWindow.add(clearTextarea);
clearTextarea.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
outputWindow.setText("");
}
});
//Сохранение в файл
Button saveSearch = new Button("Save data");
saveSearch.setBounds(570, 40, 160, 50);
mainWindow.add(saveSearch);
saveSearch.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
File file = new File("savesearch.txt");
Formatter formatter = null;
try {
formatter = new Formatter(file);
formatter.format(outputWindow.getText() + "\n");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} finally {
formatter.close();
}
}
});
mainWindow.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
File code for adding a product to a file:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class addGoodsWindow extends Frame {
public addGoodsWindow() throws HeadlessException {
String mainTitle = "Add goods";
Frame thisWindow = this;
setTitle(mainTitle);
setSize(300, 460);
setLocation(800, 360);
setVisible(false);
setLayout(null);
setResizable(false);
Label warehouseNumber = new Label("Warehouse number (required)");
warehouseNumber.setBounds(65, 30, 180, 30);
add(warehouseNumber);
TextField warehouseNumberInput = new TextField(1);
warehouseNumberInput.setBounds(10, 60, 280, 30);
add(warehouseNumberInput);
Label productName = new Label("Name of good (required)");
productName.setBounds(65, 100, 180, 30);
add(productName);
TextField productNameInput = new TextField(1);
productNameInput.setBounds(10, 130, 280, 30);
add(productNameInput);
Label price = new Label("The price of the product (required)");
price.setBounds(65, 170, 180, 30);
add(price);
TextField priceInput = new TextField(1);
priceInput.setBounds(10, 200, 280, 30);
add(priceInput);
Label count = new Label("Quantity of goods in stock (required)");
count.setBounds(65, 240, 200, 30);
add(count);
TextField countInput = new TextField(1);
countInput.setBounds(10, 270, 280, 30);
add(countInput);
Label availability = new Label("Availability (required)");
availability.setBounds(90, 310, 140, 30);
add(availability);
CheckboxGroup availabilityInput = new CheckboxGroup();
Checkbox availabilityInput1 = new Checkbox("In stock", availabilityInput, false);
availabilityInput1.setBounds(70, 340, 60, 40);
Checkbox availabilityInput2 = new Checkbox("Not availability", availabilityInput, false);
availabilityInput2.setBounds(150, 340, 90, 40);
add(availabilityInput1);
add(availabilityInput2);
Button buttonAddGoods = new Button("Add");
buttonAddGoods.setBounds(80, 380,140, 50);
add(buttonAddGoods);
buttonAddGoods.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Dialog dialog;
Checkbox checkbox = availabilityInput.getSelectedCheckbox();
try {
if (warehouseNumberInput.getText().length() != 0) {
if (productNameInput.getText().length() != 0) {
if (priceInput.getText().length() != 0) {
if (countInput.getText().length() != 0) {
if (checkbox != null) {
int warehouseNumber = Integer.parseInt(warehouseNumberInput.getText());
String productName = productNameInput.getText();
double price = Double.parseDouble(priceInput.getText());
int count = Integer.parseInt(countInput.getText());
String availability = checkbox.getLabel();
Stock obj = new Stock(warehouseNumber, productName, price, count, availability);
try {
File file = new File("database.txt");
FileOutputStream fileOutputStream;
ObjectOutputStream objectOutputStream;
if (file.exists()) {
fileOutputStream = new FileOutputStream(file, true);
objectOutputStream = new resetHeaderFile(fileOutputStream);
} else {
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
}
objectOutputStream.writeObject(obj);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException exception) {
}
warehouseNumberInput.setText("");
productNameInput.setText("");
priceInput.setText("");
countInput.setText("");
JOptionPane.showMessageDialog(thisWindow, "Add is success!");
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, check availability!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter count (integer value)!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter price!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter product name!");
}
} else {
JOptionPane.showMessageDialog(thisWindow, "Please, enter warehouse number!");
}
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(thisWindow, "Type error!");
}
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
setVisible(false);
}
});
}
}
See also full list of errors:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.iterator()" because "stocks" is null
at com.company.Main$1.mouseClicked(Main.java:68)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6629)
at java.desktop/java.awt.Component.processEvent(Component.java:6391)
at java.desktop/java.awt.Button.processEvent(Button.java:390)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Related
I'm doing a school project based on a medical store and I want to add a scroll pane to all my 3 lists that I'm using
package Interfata;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing. * ;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class Home extends JFrame {
JPanel panelHome;
static String[] listaplante = new String[10];
static String[] listacantitati = new String[10];
static String[] listapreturi = new String[10];
static int kPlante = 0,
kCantitati = 0,
kPreturi = 0;
JButton butonCumpara,
butonAdauga;
JTextField denumireField,
pretField,
cantitateField,
cantitateDoritaField;
public JPanel createHomeContentPane() {
//Creez un panel pe care sa pun toate campurile.
panelHome = new JPanel();
panelHome.setLayout(null);
panelHome.setBackground(new java.awt.Color(204, 204, 255));
panelHome.setBorder(javax.swing.BorderFactory.createTitledBorder("Home"));
//Creez lista cu plante
DefaultListModel < String > listaPlante = new DefaultListModel < >();
JList < String > list = new JList < >(citirePlante());
list.setBounds(50, 75, 75, 100);
list.setSelectionBackground(Color.ORANGE);
panelHome.add(list);
//Creez lista cu cantitatile fiecarei plante
DefaultListModel < String > listaCantitati = new DefaultListModel < >();
JList < String > list2 = new JList < >(citireCantitati());
list2.setBounds(150, 75, 75, 100);
list2.setSelectionBackground(Color.YELLOW);
panelHome.add(list2);
//Creez lista cu preturile fiecarei plante
DefaultListModel < String > listaPreturi = new DefaultListModel < >();
JList < String > list3 = new JList < >(citirePreturi());
list3.setBounds(250, 75, 75, 100);
list3.setSelectionBackground(Color.GREEN);
panelHome.add(list3);
//Creez titlurile pt fiecare lista
JLabel denumireLabel = new JLabel("Denumire:");
denumireLabel.setBounds(50, 55, 70, 20);
panelHome.add(denumireLabel);
JLabel cantitatiLabel = new JLabel("Cantitati:");
cantitatiLabel.setBounds(150, 55, 70, 20);
panelHome.add(cantitatiLabel);
JLabel preturiLabel = new JLabel("Preturi:");
preturiLabel.setBounds(250, 55, 70, 20);
panelHome.add(preturiLabel);
//Creez un camp pt a adauga cantitatea dorita care urmeaza a fi cumparata
//cantitateDoritaField
cantitateDoritaField = new JTextField();
cantitateDoritaField.setBounds(80, 200, 100, 20);
cantitateDoritaField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitateDorita = "Cantitatea dorita";
cantitateDoritaField.setText(placeholderCantitateDorita);
cantitateDoritaField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateDoritaField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateDoritaField.getText().isEmpty()) {
cantitateDoritaField.setText(placeholderCantitateDorita);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateDoritaField);
//Butonul de cumparare
butonCumpara = new JButton("Cumpara");
butonCumpara.setLocation(180, 200);
butonCumpara.setSize(100, 20);
butonCumpara.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String plantaselectata = list.getSelectedValue();
int indexplanta = list.getSelectedIndex();
String cantitateselectata = list2.getSelectedValue();
int indexcantitate = list2.getSelectedIndex();
String pretselectat = list3.getSelectedValue();
int indexpret = list3.getSelectedIndex();
String cantitatedorita = cantitateDoritaField.getText();
int valCantitate = Integer.valueOf(cantitateselectata);
int valCantitateDorita = Integer.valueOf(cantitatedorita);
int valPret = Integer.valueOf(pretselectat);
if (indexplanta == indexcantitate && indexplanta == indexpret) {
if (valCantitateDorita <= valCantitate) {
try {
afisPlantaCumparata(plantaselectata, valCantitateDorita);
} catch(IOException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
int a = valCantitate - valCantitateDorita;
String b = Integer.toString(a);
listacantitati[indexcantitate] = b;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
else {
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Cantitatea nu esti disponibila", "Eroare de cumparare", JOptionPane.WARNING_MESSAGE);
}
}
else {
JFrame rootPane = null;
JOptionPane.showMessageDialog(rootPane, "Planta, cantitate si pretul nu sunt din aceeasi categorie", "Eroare de cumparare", JOptionPane.WARNING_MESSAGE);
}
}
});
panelHome.add(butonCumpara);
//Cumpurile denumire cantitate si pret pt adaugarea plantei
//denumireField
denumireField = new JTextField();
denumireField.setBounds(80, 240, 100, 20);
denumireField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt denumireField
final String placeholderDenumire = "Denumire";
denumireField.setText(placeholderDenumire);
denumireField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
denumireField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (denumireField.getText().isEmpty()) {
denumireField.setText(placeholderDenumire);
showingPlaceholder = true;
}
}
});
panelHome.add(denumireField);
//cantitateField
cantitateField = new JTextField();
cantitateField.setBounds(80, 260, 100, 20);
cantitateField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt cantitateField
final String placeholderCantitate = "Cantitatea";
cantitateField.setText(placeholderCantitate);
cantitateField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
cantitateField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (cantitateField.getText().isEmpty()) {
cantitateField.setText(placeholderCantitate);
showingPlaceholder = true;
}
}
});
panelHome.add(cantitateField);
//pretField
pretField = new JTextField();
pretField.setBounds(80, 280, 100, 20);
pretField.setHorizontalAlignment(JTextField.CENTER);
//placeholder pt pretField
final String placeholderPret = "Pret";
pretField.setText(placeholderPret);
pretField.addFocusListener(new FocusListener() {
private boolean showingPlaceholder = true;
public void focusGained(FocusEvent e) {
if (showingPlaceholder) {
showingPlaceholder = false;
pretField.setText("");
}
}
public void focusLost(FocusEvent arg0) {
if (pretField.getText().isEmpty()) {
pretField.setText(placeholderPret);
showingPlaceholder = true;
}
}
});
panelHome.add(pretField);
//Butonul de adaugare a unei plantei noi
butonAdauga = new JButton("Adauga");
butonAdauga.setLocation(180, 260);
butonAdauga.setSize(100, 20);
butonAdauga.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
String denumireNou = denumireField.getText();
String cantitateNou = cantitateField.getText();
String pretNou = pretField.getText();
listaplante[kPlante++] = denumireNou;
listacantitati[kCantitati++] = cantitateNou;
listapreturi[kPreturi++] = pretNou;
panelHome.setVisible(false);
panelHome.setVisible(true);
}
});
panelHome.add(butonAdauga);
//Returnez panelul
panelHome.setOpaque(true);
return panelHome;
}
public static String[] citirePlante() {
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Plante.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listaplante[kPlante] = strCurrentLine;
kPlante++;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null) objReader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
return listaplante;
}
public static String[] citireCantitati() {
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Cantitati.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listacantitati[kCantitati] = strCurrentLine;
kCantitati++;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null) objReader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
return listacantitati;
}
public static String[] citirePreturi() {
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("Preturi.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
listapreturi[kPreturi] = strCurrentLine;
kPreturi++;
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null) objReader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
return listapreturi;
}
public static void afisPlantaCumparata(String p, int c) throws IOException {
FileWriter writer = new FileWriter("PlanteVandute.txt", true);
try (
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(p + " " + c + "\n");
} catch(IOException e) {
System.err.format("IOException: %s%n", e);
}
}
private static void Home() {
JFrame frameHome = new JFrame("PLAFAR * Calinescu George-Catalin * 221");
//Creez panelul peste frame si il stilizez
Home home = new Home();
frameHome.setContentPane(home.createHomeContentPane());
frameHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameHome.setSize(400, 350);
frameHome.setVisible(true);
}
public static void main(String[] args) {
//Creez GUI si il afisez pe ecran
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Home();
}
});
}
}
Is there any method I can add a scroll pane to list, list2 and list3? I really don't want to set another layout type because I'm not used to them and I worked with absolute layout when I started doing this GUI but I ran into some problems and I decided to wrote all the code by hand.
Thank you for providing example code / minimal working example. (One remark - if no Plante.txt is found an exception is thrown. You could improve your code to handle this behavior, e.g., with a warning or message for the user.)
You can add your JList to a JScrollPane like this:
// to ensure single selection in your list
someList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(someList);
Then, you have to add scollPane to a LayoutManager or (in your example) JPanel.
It's strongly recommended to use a normal layout manager, because layout manager allows to handle components sizes, when Window/Panel is resized. It's also provides better support for different Look and Feels and OS.
To get your code working you need to install scroll pane around your list.
DefaultListModel<String> listaPlante = new DefaultListModel<>();
JList<String> list = new JList<>(citirePlante());
JScrollPane scroller = new JScrollPane(list);
scroller.setBounds(50,75, 75,100); // not list!!!
list.setSelectionBackground(Color.ORANGE);
panelHome.add(scroller); // not list!!!
When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});
I'm trying to put a JComboBox on a Jpanel, if i clicked shows the contents of the combobox, but it was not showed. the content appears only if I move the cursor on top of it. the Jpanel contains a Jlabel with a picture and on top of it a Jcombobox.
PanelRegionlACTEL:
package com.springJPA.vue.appACTEL;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jd.swing.custom.component.button.StandardButton;
import com.jd.swing.custom.component.jcombobox.MyComboBoxEditor;
import com.jd.swing.custom.component.jcombobox.MyComboBoxRenderer;
import com.jd.swing.util.Theme;
import com.springJPA.domain.Numero;
import com.springJPA.domain.Region;
import com.springJPA.domain.Resedence;
import com.springJPA.service.ActelsService;
import com.springJPA.service.FonctionDAO;
import com.springJPA.service.NumeroService;
import com.springJPA.service.RegionService;
import com.springJPA.service.ResedenceService;
import com.springJPA.service.VilleService;
import com.springJPA.vue.App;
public class PanelRegionlACTEL extends JPanel {
/**
*
*/
private static final long serialVersionUID = -3805099295102746248L;
public static JComboBox<String> comboBox_gouver;
public static JComboBox<String> comboBox_ACTELS;
public static JComboBox<String> comboBoxVille;
private JButton okButton;
private JButton cancelButton;
private JProgressBar progressBar;
int value = 0;
int nbp = 0;
public int selectedIndexR;
public int selectedIndexA;
public int selectedIndexV;
public JLabel labelR1;
public boolean tr=false;
FonctionDAO fonctionDAO = new FonctionDAO();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
RegionService rgService = (RegionService) context.getBean("regionService");
ActelsService atlService = (ActelsService) context.getBean("actelService");
VilleService villeService = (VilleService) context.getBean("villeService");
NumeroService numeroService = (NumeroService) context.getBean("numeroService");
ResedenceService resedenceService = (ResedenceService) context.getBean("resedenceService");
/*public static void main(String[] args)
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception e) {
System.out.println("Erreur LookAndFeel"+e);
}
try{
new PanelAccueilACTEL();
}catch (Exception e) {
System.out.println("Erreur App: "+e);
e.printStackTrace();
}
}*/
/**
* Create the panel.
*/
public PanelRegionlACTEL() {
setLayout(null);
setBorder(null);
setOpaque(false);
setBounds(0, 0, 803, 534);
setBackground(new Color(0,0,0,0));
setSize(803, 534);
setVisible(true);
JButton buttonQuitter = new JButton("");
buttonQuitter.setIcon(new ImageIcon(PanelRegionlACTEL.class.getResource("/ap/s/tn/img/btn.PNG")));
buttonQuitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
buttonQuitter.setIcon(new ImageIcon(PanelLoginACTEL.class.getResource("/ap/s/tn/img/btn.PNG")));
buttonQuitter.setOpaque(true);
buttonQuitter.setSelectedIcon(new ImageIcon(App.class.getResource("/ap/s/tn/img/btn2.PNG")));
buttonQuitter.setFocusPainted(false);
buttonQuitter.setContentAreaFilled(false);
buttonQuitter.setBorderPainted(false);
buttonQuitter.setBounds(618, 420, 144, 41);
add(buttonQuitter);
JMenuReseau();
JMenuItemRegion();
JMenuDemandes();
JRadioButtonMenuItemNinstallation();
JRadioButtonMenuItemTransfaire();
JLabel lblLoginApplicationFta = new JLabel("Region application ACTEL");
lblLoginApplicationFta.setFont(new Font("Segoe Print", Font.BOLD, 16));
lblLoginApplicationFta.setForeground(new Color(255, 0, 0));
lblLoginApplicationFta.setBounds(6, 6, 229, 28);
add(lblLoginApplicationFta);
JLabel lblslectionnerUnGouvernorat = new JLabel("<html><font color='#09024D'>S\u00E9lectionner un gouvernorat</font></html>");
lblslectionnerUnGouvernorat.setFont(new Font("SansSerif", Font.PLAIN, 18));
lblslectionnerUnGouvernorat.setBounds(54, 107, 242, 25);
add(lblslectionnerUnGouvernorat);
comboBox_gouver = new JComboBox<String>();
comboBox_gouver.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
afficherLISTE_REGION();
comboBox_gouver.setBounds(323, 106, 118, 26);
comboBox_gouver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedIndexR = comboBox_gouver.getSelectedIndex();
selectedIndexA = comboBox_ACTELS.getSelectedIndex();
if(selectedIndexR == 0) {
comboBox_ACTELS.setModel(new DefaultComboBoxModel<String> (new String[] {"---------------------"}));
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
}
else{
afficherLISTE_ACTEL_PAR_REGION();
}
}
});
add(comboBox_gouver);
comboBox_ACTELS = new JComboBox<String>();
//comboBox_ACTELS.setRenderer(new MyComboBoxRenderer());
//comboBox_ACTELS.setEditor(new MyComboBoxEditor());
comboBox_ACTELS.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
comboBox_ACTELS.setBounds(323, 134, 118, 26);
comboBox_ACTELS.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e2) {
int indexA = comboBox_ACTELS.getSelectedIndex();
if(indexA == 0){
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
}
else{
afficherLISTE_VILLE_PAR_ACTEL();
}
}
});
JLabel lblchoixActels = new JLabel("<html><font color='#09024D'>Choix ACTELS</font></html>");
lblchoixActels.setFont(new Font("SansSerif", Font.PLAIN, 18));
lblchoixActels.setBounds(54, 139, 133, 16);
add(lblchoixActels);
add(comboBox_ACTELS);
JLabel lblville = new JLabel("<html><font color='#09024D'>Ville</font></html>");
lblville.setFont(new Font("SansSerif", Font.PLAIN, 18));
lblville.setBounds(54, 170, 42, 16);
add(lblville);
comboBoxVille = new JComboBox<String>();
comboBoxVille.setBounds(323, 165, 118, 26);
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
add(comboBoxVille);
progressBar = new JProgressBar();
progressBar.setBounds(54, 198, 154, 19);
progressBar.setVisible(false);
add(progressBar);
StandardButton button = new StandardButton("OK", Theme.GLOSSY_BLUE_THEME);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
App.cl_conteneurPaneau.show(App.conteneurPaneau, "panelAccueilACTEL");
int indexRegion = comboBox_gouver.getSelectedIndex();
int indexActel = comboBox_ACTELS.getSelectedIndex();
int indexVille = comboBoxVille.getSelectedIndex();
String region = comboBox_gouver.getSelectedItem().toString();
String ville = comboBoxVille.getSelectedItem().toString();
if((indexRegion==0)&&(indexActel==0)&&(indexVille==0)){
labelR1.setText("selectioner tout champs");
}
else if((indexActel==0)&&(indexVille==0)){
labelR1.setText("selectioner tout champs");
}
else{
action();
labelR1.setForeground(new Color(0, 128, 0));
labelR1.setText("region : "+region);
region = comboBox_gouver.getSelectedItem().toString();
ville = comboBoxVille.getSelectedItem().toString();
PanelAccueilACTEL.getLabelR().setText("<html><body><b>Region: "+region+"</b></body></html>");
PanelAccueilACTEL.getLabelV().setText("<html><body><b>*Ville: "+ville+"</b></body></html>");
remplir_code_postal();
remplir_numero();
remplir_type_voie();
}
}
});
button.setActionCommand("OK");
button.setBounds(54, 250, 80, 28);
add(button);
ImageIcon icon = new ImageIcon(getClass().getResource("/tn/pack/image/cadre-rg.png"));
Image zoom = scaleImage(icon.getImage(), 934);
Icon iconScaled = new ImageIcon(zoom);
labelR1 = new JLabel("");
labelR1.setBounds(250, 258, 133, 14);
add(labelR1);
JLabel cadre = new JLabel(iconScaled);
cadre.setIcon(new ImageIcon(PanelLoginACTEL.class.getResource("/tn/pack/image/cadre-rg.png")));
cadre.setBounds(6, 70, 486, 305);
add(cadre);
JLabel arrirePlan = new JLabel("");
arrirePlan.setIcon(new ImageIcon(PanelRegionlACTEL.class.getResource("/ap/s/tn/img/bot.png")));
arrirePlan.setBounds(0, 0, 803, 534);
add(arrirePlan);
}
public void remplir_type_voie() {
List<Resedence> listeTypeVoie = fonctionDAO.afficherLISTE_TYPE_VOIE(resedenceService);
for(Resedence resedence:listeTypeVoie) {
PanelNouvelleInstallation.comboBox_typeVoie.addItem(resedence.getType_voie());
PanelDemandeTransfertACTEL.comboBox_typeVoieA.addItem(resedence.getType_voie());
PanelDemandeTransfertACTEL.comboBox_typeVoieN.addItem(resedence.getType_voie());
}
}
public void remplir_code_postal() {
PanelNouvelleInstallation.textField_codepostal.setText(getcodePostal()+"");
PanelDemandeTransfertACTEL.textField_codepostalA.setText(getcodePostal()+"");
PanelDemandeTransfertACTEL.textField_codepostalN.setText(getcodePostal()+"");
}
protected void afficherLISTE_VILLE_PAR_ACTEL() {
try {
comboBoxVille.removeAllItems();
String nom_actel = comboBox_ACTELS.getSelectedItem().toString();
int id_actel = fonctionDAO.afficherID_ACTEL_PAR_NOM_ACTEL(atlService, nom_actel);
List<String> listeVille= fonctionDAO.afficherLISTE_VILLE_PAR_ACTEL(villeService, id_actel);
for(String lv:listeVille) {
comboBoxVille.addItem(lv);
}
} catch (Exception e1) {
System.out.println("Erreur SELECT ville");
}
}
protected void afficherLISTE_ACTEL_PAR_REGION() {
comboBox_ACTELS.setModel(new DefaultComboBoxModel<String> (new String[] {"---------------------"}));
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
List<String> listeActel= fonctionDAO.afficherLISTE_ACTEL_PAR_REGION(atlService, comboBox_gouver.getSelectedIndex()+49);
for(String la:listeActel) {
comboBox_ACTELS.addItem(la);
}
}
private void afficherLISTE_REGION() {
List<Region> listeRegion= fonctionDAO.afficherLISTE_REGION(rgService);
for(Region lr:listeRegion) {
comboBox_gouver.addItem(lr.getNom_region());
}
}
private void JRadioButtonMenuItemTransfaire() {
}
private void JRadioButtonMenuItemNinstallation() {
}
private void JMenuDemandes() {
}
private void JMenuItemRegion() {
}
private void JMenuReseau() {
}
void action() {
new Thread(new Runnable() {
public void run() {
try {
progressBar.setValue(value);
value++;
Thread.sleep(15);
}
catch (InterruptedException ex) {ex.printStackTrace();}
if (progressBar.getPercentComplete() == 1.0) {
tr=true;
}
else { tr=false;
action();}
}
}).start();
}
public int remplir_numero() {
String ville = comboBoxVille.getSelectedItem().toString();
Listnumero.listModel.removeAllElements();
PanelAffectationNumero.comboBox_choixN.removeAllItems();
PanelAffectationNumero.comboBox_choixN.setEnabled(false);
List<Numero> listeNum = fonctionDAO.afficherLISTE_NUMERO(numeroService, fonctionDAO.afficherID_VILLE_PAR_NOM_VILLE(villeService, ville));
if(listeNum!=null){
for(Numero ln:listeNum) {
Listnumero.listModel.addElement(ln.getPlage_numero()+"");
}
return 1;
}
else{
return 0;
}
}
/* public int remplir_resedence(){
PanelNouvelleInstallation.comboBoxResedence.setModel(new DefaultComboBoxModel<String>(new String[] {"-----------"}));
String nom_ville = comboBoxVille.getSelectedItem().toString();
List<Ville> listeVille = fonctionDAO.afficherRESEDENCE_PAR_NOM_VILLE(villeService, nom_ville);
if(listeVille!=null){
for(Ville lv:listeVille) {
PanelNouvelleInstallation.comboBoxResedence.addItem(lv.getResedence());
}
return 1;
}
else{
return 0;
}
}*/
/* public void remplir_voie(){
int indextvoie= PanelNouvelleInstallation.comboBoxTypeVoie.getSelectedIndex();
String type_voie = PanelNouvelleInstallation.comboBoxTypeVoie.getSelectedItem().toString();
String nom_ville = PanelRegionlACTEL.comboBoxVille.getSelectedItem().toString();
if(indextvoie == 0){
PanelNouvelleInstallation.comboBoxVoie.setModel(new DefaultComboBoxModel<String>(new String[] {"----------------"}));
}
else{
PanelNouvelleInstallation.comboBoxVoie.setModel(new DefaultComboBoxModel<String>(new String[] {"----------------"}));
List<Ville> listeVille = fonctionDAO.afficherVOIE_PAR_NOM_VILLE(villeService, nom_ville, type_voie);
if(listeVille!=null){
for(Ville lv: listeVille){
PanelNouvelleInstallation.comboBoxVoie.addItem(lv.getVoie());
}
}
}
}*/
public int getcodePostal() {
String nom_actel = comboBox_ACTELS.getSelectedItem().toString();
String nom_ville = comboBoxVille.getSelectedItem().toString();
return fonctionDAO.afficherCODEP_PAR_NOM_VILLE(villeService, fonctionDAO.afficherNUM_ACTEL_PAR_NOM_ACTEL(atlService, nom_actel)+50, nom_ville);
}
public JButton getOkButton() {
return okButton;
}
public void setOkButton(JButton okButton) {
this.okButton = okButton;
}
public JButton getCancelButton() {
return cancelButton;
}
public void setCancelButton(JButton cancelButton) {
this.cancelButton = cancelButton;
}
public static Image scaleImage(Image source, int width, int height) {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(source, 0, 0, width, height, null);
g.dispose();
return img;
}
//avec une taille en pixels (=hauteur si portrait, largeur si paysage):
public static Image scaleImage(Image source, int size) {
int width = source.getWidth(null);
int height = source.getHeight(null);
double f = 0;
if (width < height) {//portrait
f = (double) height / (double) width;
width = (int) (size / f);
height = size;
} else {//paysage
f = (double) width / (double) height;
width = size;
height = (int) (size / f);
}
return scaleImage(source, width, height);
}
}
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.
I am creating a program that will take the data from several textboxes store in an array and when a next and previous button are pressed display the next or last position in the array, currently the next button gets stuck in a while loop without displaying and I'm not sure how to fix it, I am an amateur and I need help with this.
package major;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.List;
import java.awt.Label;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class gui {
private JFrame frame;
private JTextField websitetxt;
private JTextField usernametxt;
private JTextField passwordtxt;
private encryptedData[] dataArray;
private int dataArrayMaxIndex;
private int dataArrayMax;
private int dataArrayCurrentIndex;
private JButton btnadd;
private JButton btnnew;
private JButton btndelete;
private JTextField notestxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public gui() {
initialize();
dataArrayMax = 20;
dataArray = new encryptedData[dataArrayMax];
dataArrayMaxIndex = 0;
while (dataArrayMaxIndex < dataArrayMax) {
dataArray[dataArrayMaxIndex] = new encryptedData();
dataArrayMaxIndex++;
}
dataArrayMaxIndex = -1;
dataArrayCurrentIndex = -1;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 569, 427);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
websitetxt = new JTextField();
websitetxt.setBounds(315, 56, 191, 38);
frame.getContentPane().add(websitetxt);
websitetxt.setColumns(10);
usernametxt = new JTextField();
usernametxt.setColumns(10);
usernametxt.setBounds(315, 105, 191, 38);
frame.getContentPane().add(usernametxt);
passwordtxt = new JTextField();
passwordtxt.setColumns(10);
passwordtxt.setBounds(315, 154, 191, 38);
frame.getContentPane().add(passwordtxt);
JLabel lblWebsite = new JLabel("Website:");
lblWebsite.setBounds(227, 68, 78, 14);
frame.getContentPane().add(lblWebsite);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(227, 117, 78, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(227, 166, 78, 14);
frame.getContentPane().add(lblPassword);
final JButton btnadd = new JButton("Add to Database");
btnadd.setEnabled(false);
btnadd.setBounds(10, 105, 191, 38);
frame.getContentPane().add(btnadd);
JLabel lblPasswordManagerHsc = new JLabel("Password manager hsc 2014");
lblPasswordManagerHsc.setBounds(191, 11, 168, 14);
frame.getContentPane().add(lblPasswordManagerHsc);
final JButton btnnew = new JButton("New Record");
btnnew.setBounds(10, 56, 191, 38);
frame.getContentPane().add(btnnew);
JButton btndelete = new JButton("Delete Record");
btndelete.setBounds(10, 154, 191, 38);
frame.getContentPane().add(btndelete);
JButton btnprev = new JButton("Prev");
btnprev.setBounds(315, 316, 89, 23);
frame.getContentPane().add(btnprev);
JButton btnnext = new JButton("Next");
btnnext.setBounds(417, 316, 89, 23);
frame.getContentPane().add(btnnext);
notestxt = new JTextField();
notestxt.setBounds(315, 203, 191, 102);
frame.getContentPane().add(notestxt);
notestxt.setColumns(10);
JLabel lblnotes = new JLabel("Notes");
lblnotes.setBounds(227, 215, 46, 14);
frame.getContentPane().add(lblnotes);
JButton btngenerate = new JButton("Generate Password");
btngenerate.setBounds(10, 203, 191, 38);
frame.getContentPane().add(btngenerate);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem save = new JMenuItem("Save");
File.add(save);
JMenuItem load = new JMenuItem("Load");
File.add(load);
JMenuItem mntmHelp = new JMenuItem("About");
File.add(mntmHelp);
websitetxt.setEnabled(false);
usernametxt.setEnabled(false);
passwordtxt.setEnabled(false);
notestxt.setEnabled(false);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnadd.setEnabled(false);
dataArrayCurrentIndex++;
dataArrayMaxIndex++;
dataArray[dataArrayCurrentIndex].username = usernametxt.getText();
dataArray[dataArrayCurrentIndex].password = passwordtxt.getText();
dataArray[dataArrayCurrentIndex].notes = notestxt.getText();
dataArray[dataArrayCurrentIndex].website = websitetxt.getText();
}
});
btnnew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnnew) {
websitetxt.setEnabled(true);
usernametxt.setEnabled(true);
passwordtxt.setEnabled(true);
notestxt.setEnabled(true);
btnadd.setEnabled(true);
websitetxt.setText("");
usernametxt.setText("");
passwordtxt.setText("");
notestxt.setText("");
}
}
});
btndelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnprev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i < dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
}
}
package major;
public class encryptedData {
public String website;
public String username;
public String password;
public String notes;
public encryptedData() {
try {
website = "";
username = "";
password = "";
notes = "";
} catch (Exception e) {
}
}
public encryptedData(String w, String u, String p, String n) {
try {
website = w;
username = u;
password = p;
notes = n;
} catch (Exception e) {
}
}
//Access methods
public String getWebsitename() {
return website;
}
public void setWebsiteName(String w) {
website = w;
}
public String getUsername() {
return username;
}
public void setUsername(String u) {
username = u;
}
public String getPassword() {
return password + "";
}
public void setPassword(String p) {
password = p;
}
public String getNotes() {
return notes + "";
}
public void setNotes(String n) {
notes = n;
}
}
You are incrementing i after the while loop in actionPerformed()!
If you had formatted your code better, this would have been obvious:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i<dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
And this would have been even better:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i<dataArrayMaxIndex; i++) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
}
});