Getting a value back from an array using a random method - java

I am having issues with getting a correct value from my random method I am using. Everything else in my code works, but when I hit the random message button, I get an output on null null null null null instead of a random value from each array. My code is below. Any help to solve this would be greatly appreciated.
package shoutbox;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
public class ShoutBox {
String subj, obj, verB, adJ, adV, cannedM, randomM, tempSubj, tempObj, tempAdj, tempVerb, tempAdverb;
private final String[] stringItems = {
"I was sent here by the king to slay you!",
"I will leave you to your slumber.",
"I heard you have a piece of treasure I am interested in.",
"I heard you know a way to save princess Layla from illness.",
"Might I say you look lovely in the moonight.",
"I love dragons!",
"I will slay you and take your treasure!",
"Are you a luck dragon?",
"I think I will turn around and go home now.",
"Go ahead and try to roast me with your fire! I am a wizard, I will prevail!"
};
private final String[] subject = {
"I", "You", "Everyone", "They", "The King", "The Queen", "My Brother",
"We", "The gold", "The book"
};
private final String[] object = {
"sword", "treasure", "dragon", "cave", "head", "friends", "fire",
"blood", "jewels", "magic"
};
private final String[] verb = {
"yells", "hits", "torches", "sings", "laughs", "loves", "dances",
"scouts", "hates", "wants"
};
private final String[] adjective = {
"beautiful", "outragious", "pretty", "scary", "lazy", "heavy", "enormous",
"hot", "scaly", "scary"
};
private final String[] adverb = {
"quickly", "slowly", "softly", "skillfully", "wickedly", "underground", "tomorrow",
"uneasily", "quickly", "abruptly"
};
public void setSubject(String tempSubj) {
tempSubj = subj;
}
public void setObject(String tempObj) {
tempObj = obj;
}
public void setVerb(String tempVerb) {
tempVerb = verB;
}
public void setAdjective(String tempAdj) {
tempAdj = adJ;
}
public void setAdverb(String tempAdverb) {
tempAdverb = adV;
}
public String getSubject() {
Random genSub = new Random();
int randomSub = genSub.nextInt(subject.length);
subj = subject[randomSub];
return subj;
}
public String getObject() {
Random genOb = new Random();
int randomOb = genOb.nextInt(object.length);
obj = object[randomOb];
return obj;
}
public String getVerb() {
Random genVerb = new Random();
int randomVerb = genVerb.nextInt(verb.length);
verB = subject[randomVerb];
return verB;
}
public String getAdjective() {
Random genAd = new Random();
int randomAd = genAd.nextInt(adjective.length);
adJ = adjective[randomAd];
return adJ;
}
public String getAdverb() {
Random genAdverb = new Random();
int randomAdverb = genAdverb.nextInt(adverb.length);
adV = subject[randomAdverb];
return adV;
}
public ShoutBox() {
JFrame frame = new JFrame(); //setting up Jframe components
// Setting width, height, and title of window
frame.setTitle("Shout Box");
frame.setSize(450, 400); // Size of frame window
frame.setLocation(360, 200); // Start location of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false); // So you cannot resize frame
JButton submitButton = new JButton("Submit");
JButton randomButton = new JButton("Random Message");
JLabel label = new JLabel("Pick a message and click submit or click random message");
JList JlistMap;
JTextArea textArearesult = new JTextArea(2, 21);
textArearesult.setEditable(false);
textArearesult.setLineWrap(true);
textArearesult.setWrapStyleWord(true);
JPanel panel = new JPanel();
JLabel label1 = new JLabel("");
label1.setForeground(Color.blue);
JLabel label2 = new JLabel(" Your Message you have chosen is: ");
label2.setForeground(Color.red);
JlistMap = new JList(stringItems);
JlistMap.setVisibleRowCount(10);
JlistMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//add(new JScrollPane(JlistMap)); //Not working as of now
panel.setBackground(Color.PINK); // Pink background color
frame.add(panel);
panel.add(label);
panel.add(JlistMap);
panel.add(submitButton);
panel.add(randomButton);
panel.add(label2);
panel.add(textArearesult);
// Action Listener for the submit button to get the message that will display in the JTextArea
submitButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutCannedMessage()); //using ShoutOutCannedMessage method to return cannedM
});
randomButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutRandomMessage()); //using ShoutOutCannedMessage method to return cannedM
});
// JList will get the selected Item and set the item to a string value t that will be set to cannedM
JlistMap.addListSelectionListener((ListSelectionEvent e) -> {
JList list = (JList) e.getSource();
String t = list.getSelectedValue().toString();
cannedM = t;
});
frame.setVisible(true); //set to be visible on panel
}
public String ShoutOutCannedMessage() {
return cannedM;
}
public String ShoutOutRandomMessage() {
randomM = tempSubj + " " + tempObj + " " + tempVerb + " " + tempAdj + " " + tempAdverb + ".";
return randomM;
}
}
package shoutbox;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
public class ShoutBox {
String cannedM, randomM, subJ, tempSubj, tempObj, tempAdj, tempVerb, tempAdverb;
private final String[] stringItems = {
"I was sent here by the king to slay you!",
"I will leave you to your slumber.",
"I heard you have a piece of treasure I am interested in.",
"I heard you know a way to save princess Layla from illness.",
"Might I say you look lovely in the moonight.",
"I love dragons!",
"I will slay you and take your treasure!",
"Are you a luck dragon?",
"I think I will turn around and go home now.",
"Go ahead and try to roast me with your fire! I am a wizard, I will prevail!"
};
private final String[] subject = {
"I", "You", "Everyone", "They", "The King", "The Queen", "My Brother",
"We", "The gold", "The book"
};
private final String[] object = {
"sword", "treasure", "dragon", "cave", "head", "friends", "fire",
"blood", "jewels", "magic"
};
private final String[] verb = {
"yells", "hits", "torches", "sings", "laughs", "loves", "dances",
"scouts", "hates", "wants"
};
private final String[] adjective = {
"beautiful", "outragious", "pretty", "scary", "lazy", "heavy", "enormous",
"hot", "scaly", "scary"
};
private final String[] adverb = {
"quickly", "slowly", "softly", "skillfully", "wickedly", "underground", "tomorrow",
"uneasily", "quickly", "abruptly"
};
public void setSubject() {
Random genSub = new Random();
int randomSub = genSub.nextInt(subject.length);
tempSubj = subject[randomSub];
}
public void setObject() {
Random genOb = new Random();
int randomOb = genOb.nextInt(object.length);
tempObj = object[randomOb];
}
public void setVerb() {
Random genVerb = new Random();
int randomVerb = genVerb.nextInt(verb.length);
tempVerb = verb[randomVerb];
}
public void setAdjective() {
Random genAd = new Random();
int randomAd = genAd.nextInt(adjective.length);
tempAdj = adjective[randomAd];
}
public void setAdverb() {
Random genAdverb = new Random();
int randomAdverb = genAdverb.nextInt(adverb.length);
tempAdverb = subject[randomAdverb];
}
public String getSubject() {
return tempSubj;
}
public String getObject() {
return tempObj;
}
public String getVerb() {
return tempVerb;
}
public String getAdjective() {
return tempAdj;
}
public String getAdverb() {
return tempAdverb;
}
public ShoutBox() {
JFrame frame = new JFrame(); //setting up Jframe components
// Setting width, height, and title of window
frame.setTitle("Shout Box");
frame.setSize(450, 400); // Size of frame window
frame.setLocation(360, 200); // Start location of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false); // So you cannot resize frame
JButton submitButton = new JButton("Submit");
JButton randomButton = new JButton("Random Message");
JLabel label = new JLabel("Pick a message and click submit or click random message");
JList JlistMap;
JTextArea textArearesult = new JTextArea(1, 30);
textArearesult.setEditable(false);
textArearesult.setLineWrap(true);
textArearesult.setWrapStyleWord(true);
JPanel panel = new JPanel();
JLabel label1 = new JLabel("");
label1.setForeground(Color.blue);
JLabel label2 = new JLabel(" Your Message you have chosen is: ");
label2.setForeground(Color.red);
JlistMap = new JList(stringItems);
JlistMap.setVisibleRowCount(10);
JlistMap.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//add(new JScrollPane(JlistMap)); //Not working as of now
panel.setBackground(Color.PINK); // Pink background color
frame.add(panel);
panel.add(label);
panel.add(JlistMap);
panel.add(submitButton);
panel.add(randomButton);
panel.add(label2);
panel.add(textArearesult);
// Action Listener for the submit button to get the message that will display in the JTextArea
submitButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutCannedMessage()); //using ShoutOutCannedMessage method to return cannedM
});
randomButton.addActionListener((ActionEvent e) -> {
textArearesult.setText(ShoutOutRandomMessage()); //using ShoutOutCannedMessage method to return cannedM
});
// JList will get the selected Item and set the item to a string value t that will be set to cannedM
JlistMap.addListSelectionListener((ListSelectionEvent e) -> {
JList list = (JList) e.getSource();
String t = list.getSelectedValue().toString();
cannedM = t;
});
frame.setVisible(true); //set to be visible on panel
}
public String ShoutOutCannedMessage() {
return cannedM;
}
public String ShoutOutRandomMessage() {
randomM = getSubject() + " " + getObject() + " " + getVerb() + " " + getAdjective() + " " + getAdverb() + ".";
return randomM;
}
}

You have to set the values of your attributes tempSubj, tempObj, tempVerb, tempAdjand tempAdverb.
Notice that you've declare these attributes but you haven't affect them with any value. Therefore, they assume the value null.
In order to fix this, you have set them with some value explicitly or invoke their setters, which you've already created. Also you've to fix your setters because they're not properly setting your attributes:
public void setSubject(String subj) {
tempSubj = subj;
}
public void setObject(String obj) {
tempObj = obj;
}
public void setVerb(String verb) {
tempVerb = verb;
}
public void setAdjective(String adj) {
tempAdj = adj;
}
public void setAdverb(String adv) {
tempAdverb = adv;
}
EDIT
Other approach, is to use your getters, where you have the random code logic:
public String ShoutOutRandomMessage() {
randomM = getSubject() + " " + getObject() + " " + getVerb() + " " + getAdjective() + " " + getAdverb() + ".";
return randomM;
}

Related

JTextArea not updating when selection changes in JComboBox

I am trying to add a class for each course in the drop down menu on the right corner of the image, as shown in the code in the action Performed there is one class but the same class opens for all the courses so how can i make each one of them open a different class?
this part is confusing me im not sure if i need to do anything with it or not
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
the list of courses in the left corner works perfectly fine with me but my only problem is instead of the list on the left i want the list on the right to work and it has something to do with crse
public class CourseWork extends JFrame implements ActionListener, KeyListener {
CommonCode cc = new CommonCode();
JPanel pnl = new JPanel(new BorderLayout());
JTextArea txtNewNote = new JTextArea();
JTextArea txtDisplayNotes = new JTextArea();
JTextField search = new JTextField();
ArrayList<String> note = new ArrayList<>();
ArrayList<String> course = new ArrayList<>();
JComboBox courseList = new JComboBox();
String crse = "";
AllNotes allNotes = new AllNotes();
public static void main(String[] args) {
// This is required for the coursework.
//JOptionPane.showMessageDialog(null, "Racha Chaouby");
CourseWork prg = new CourseWork();
}
// Using MVC
public CourseWork() {
model();
view();
controller();
}
#Override
public void actionPerformed(ActionEvent ae) {
if ("Close".equals(ae.getActionCommand())) {
}
if ("Course".equals(ae.getActionCommand())) {
crse = courseList.getSelectedItem().toString();
COMP1752 cw = new COMP1752();
}
if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
}
if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
}
if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
}
if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
if ("Course1752".equals(ae.getActionCommand())) {
COMP1752 cw = new COMP1752();
}
if ("Course1753".equals(ae.getActionCommand())) {
COMP1753 cw = new COMP1753();
}
if ("Cours1110".equals(ae.getActionCommand())) {
MATH1110 cw = new MATH1110();
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped not coded yet.");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed not coded yet.");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased not coded yet.");
}
private void model() {
course.add("COMP1752");
course.add("COMP1753");
course.add("MATH1110");
crse = course.get(0);
//Note nt = new Note();
//nt.noteID = 1;
//t.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "Arrays are of fixed length and are inflexible.";
//allNotes.allNotes.add(nt);
//nt = new Note();
//nt.noteID = 2;
//nt.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "ArraysList can be added to and items can be deleted.";
//allNotes.allNotes.add(nt);
}
private void view() {
Font fnt = new Font("Georgia", Font.PLAIN, 24);
JMenuBar menuBar = new JMenuBar();
JMenu kurs = new JMenu();
kurs = new JMenu("Courses");
kurs.setToolTipText("Course tasks");
kurs.setFont(fnt);
kurs.add(makeMenuItem("COMP1752", "Course1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("COMP1753", "Course1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("MATH1110", "Course1110", "Coursework requirments.", fnt));
menuBar.add(kurs);
JMenu note = new JMenu();
note = new JMenu("Note");
note.setToolTipText("Note tasks");
note.setFont(fnt);
note.add(makeMenuItem("New", "NewNote", "Create a new note.", fnt));
note.addSeparator();
note.add(makeMenuItem("Close", "Close", "Clear the current note.", fnt));
menuBar.add(note);
menuBar.add(makeMenuItem("Exit", "Exit", "Close this program", fnt));
// This will add each course to the combobox
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
this.setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
// Setting up the ButtonBar
JButton button = null;
button = makeButton("Document", "Coursework",
"Open the coursework window.",
"Coursework");
toolBar.add(button);
button = makeButton("Create", "NewNote",
"Create a new note.",
"New");
toolBar.add(button);
button = makeButton("closed door", "Close",
"Close this note.",
"Close");
toolBar.add(button);
toolBar.addSeparator();
button = makeButton("exit button", "Exit",
"Exit from this program.",
"Exit");
toolBar.add(button);
toolBar.addSeparator();
// This forces anything after it to the right.
toolBar.add(Box.createHorizontalGlue());
search.setMaximumSize(new Dimension(6900, 30));
search.setFont(fnt);
toolBar.add(search);
toolBar.addSeparator();
button = makeButton("search", "SearchKeyword",
"Search for this text.",
"Search");
toolBar.add(button);
add(toolBar, BorderLayout.NORTH);
JPanel pnlWest = new JPanel();
pnlWest.setLayout(new BoxLayout(pnlWest, BoxLayout.Y_AXIS));
pnlWest.setBorder(BorderFactory.createLineBorder(Color.black));
txtNewNote.setFont(fnt);
pnlWest.add(txtNewNote);
JButton btnAddNote = new JButton("Add note");
btnAddNote.setActionCommand("NewNote");
btnAddNote.addActionListener(this);
pnlWest.add(btnAddNote);
add(pnlWest, BorderLayout.WEST);
JPanel cen = new JPanel();
cen.setLayout(new BoxLayout(cen, BoxLayout.Y_AXIS));
cen.setBorder(BorderFactory.createLineBorder(Color.black));
txtDisplayNotes.setFont(fnt);
cen.add(txtDisplayNotes);
add(cen, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Coursework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Needed to ensure that the items can be seen.
}
private void controller() {
addAllNotes();
}
protected JMenuItem makeMenuItem(
String txt,
String actionCommand,
String toolTipText,
Font fnt) {
JMenuItem mnuItem = new JMenuItem();
mnuItem.setText(txt);
mnuItem.setActionCommand(actionCommand);
mnuItem.setToolTipText(toolTipText);
mnuItem.setFont(fnt);
mnuItem.addActionListener(this);
return mnuItem;
}
protected JButton makeButton(
String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.setActionCommand(actionCommand);
button.addActionListener(this);
//Look for the image.
String imgLocation = System.getProperty("user.dir")
+ "\\icons\\"
+ imageName
+ ".png";
File fyle = new File(imgLocation);
if (fyle.exists() && !fyle.isDirectory()) {
// image found
Icon img;
img = new ImageIcon(imgLocation);
button.setIcon(img);
} else {
// image NOT found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
private void addNote(String text) {
allNotes.addNote(allNotes.getMaxID(), crse, text);
addAllNotes();
}
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotes()) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
public String getDateAndTime() {
String UK_DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
String ukDateAndTime;
Calendar cal = Calendar.getInstance();
SimpleDateFormat uksdf = new SimpleDateFormat(UK_DATE_FORMAT_NOW);
ukDateAndTime = uksdf.format(cal.getTime());
return ukDateAndTime;
}
}
code snippet
this is the AllNotes class:
public class AllNotes extends CommonCode {
private ArrayList<Note> allNotes = new ArrayList<>();
private String crse = "";
private int maxID = 0;
AllNotes() {
readAllNotes();
}
public final int getMaxID() {
maxID++;
return maxID;
}
private void readAllNotes() {
ArrayList<String> readNotes = new ArrayList<>();
readNotes = readTextFile(appDir + fileSeparator + "Notes.txt");
System.out.println(readNotes.get(0));
if (!"File not found".equals(readNotes.get(0))) {
allNotes.clear();
for (String str : readNotes) {
String[] tmp = str.split("\t");
int nid = Integer.parseInt(tmp[0]);
Note n = new Note(nid, tmp[1], tmp[2], tmp[3]);
allNotes.add(n);
if (nid > maxID) {
maxID = nid;
}
}
}
maxID++;
}
public void addNote(int maxID, String course, String note) {
Note myNote = new Note(maxID, course, note);
allNotes.add(myNote);
writeAllNotes();
}
public ArrayList<Note> getAllNotes() {
return allNotes;
}
private void writeAllNotes() {
String path = appDir + fileSeparator +"Notes.txt";
ArrayList<String> writeNote = new ArrayList<>();
for (Note n : allNotes) {
String tmp = n.getNoteID() + "\t";
tmp += n.getCourse() + "\t";
tmp += n.getDayte() + "\t";
tmp += n.getNote();
writeNote.add(tmp);
}
try {
writeTextFile(path, writeNote);
} catch (IOException ex) {
System.out.println("Problem! " + path);
}
}
public String searchAllNotesByKeyword(String noteList, int i, String s) {
if (i == allNotes.size()) {
return noteList;
}
if (allNotes.get(i).getNote().contains(s)) {
noteList += allNotes.get(i).getNote() + "\n";
}
return searchAllNotesByKeyword(noteList, i + 1, s);
}
}
When you init your drop down of courses, set the action command to be the same value that you record in your file, this will make everything consistent when looking up notes from the file. so this way
kurs.add(makeMenuItem("Course 1752", "COMP1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1753", "COMP1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1110", "MATH1110", "Coursework requirments.", fnt));
Then change actionPerformed to store the selected value form the drop down to the crse attribute, and call addAllNotes() to refresh the notes list
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed: " + ae.getActionCommand());
if ("Close".equals(ae.getActionCommand())) {
} else if ("Course".equals(ae.getActionCommand())) {
// set the value of the selected element into the crse attribute
crse = courseList.getSelectedItem().toString();
// Refresh the text area
addAllNotes();
} else if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
} else if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
} else if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
} else if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
System.out.println("selectedCourse: " + crse);
}
in AllNotes, create a new method to return the notes for a specific course.
public ArrayList<Note> getAllNotesForCourse(String course) {
ArrayList<Note> notes = new ArrayList<>();
for(Note note : allNotes) {
if(course.equalsIgnoreCase(note.getCourse())) {
notes.add(note);
}
}
return notes;
}
then in the addAllNotes method, call getAllNotesForCourse, passing the selected course. This will update txtDisplayNotes with the notes from the selected course
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotesForCourse(crse)) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
I think this is all I modified and it works for me.

Why does it say -XLint:Deprecation when I run my program in cmd?

I am having issues compiling it through the window's own cmd.
Now the Issue I get is as follows:
Note: ApplicationCentre.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
When I do compile with it I get the following error:
ApplicationCentre.java:7: warning: [deprecation] JApplet in javax.swing has been deprecated
public class ApplicationCentre extends JApplet implements ActionListener{
I have all my files in one folder name: applicationCentre
the folder contains: ApplicationCentre.java and ApplicationCentre.html
The code is posted below:
import java.awt.event.*;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ApplicationCentre extends JApplet implements ActionListener{
private static final long serialVersionUID = 1L;
public ApplicationCentre() {
}
JTextField t1,t2;
JLabel l3,l4;
JButton b1,b2,b3,b4;
String best = "";
Student stu[];
JScrollPane listScrollPane = new JScrollPane();
String[] uni = {"Toronto","York","Western","Brock","Guelph","Waterloo","McGill","Concordia","Laval","Macmaster"};
JList<?> uniList = new JList<Object>(uni);
CardLayout cardManager = new CardLayout();
JPanel cards = new JPanel(cardManager);
int count = 0;
Object[] values;
String userName;
int avgMark;
ArrayList<String> nameList = new ArrayList<String>();
ArrayList<String> markList = new ArrayList<String>();
public void init() {
//Added Buttons
stu = new Student[20];
Container c = this.getContentPane();
JPanel p1 = new JPanel();
b1 = new JButton("Input");
b2 = new JButton("Display All");
b3 = new JButton("Search");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
p1.setLayout(new GridLayout(3,1));
p1.add(b1);
p1.add(b2);
p1.add(b3);
c.add(p1, BorderLayout.WEST);
//Added Labels, TextFields and JList
JPanel p2 = new JPanel();
JLabel l1 = new JLabel("Enter Students Name. ");
t1 = new JTextField();
JLabel l2 = new JLabel("Enter Average Mark. ");
t2 = new JTextField();
JLabel l3 = new JLabel("From the List below choose 3 universities. ");
uniList.setVisibleRowCount(2);
listScrollPane.setViewportView(uniList);
b4 = new JButton("Submit");
p2.setLayout(new GridLayout(0,1));
p2.add(l1);
p2.add(t1);
p2.add(l2);
p2.add(t2);
p2.add(l3);
p2.add(listScrollPane);
p2.add(b4);
c.add(p2, BorderLayout.EAST);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
userName = t1.getText();
avgMark = Integer.parseInt(t2.getText());
values = uniList.getSelectedValuesList().toArray();
if(e.getSource()==b4) {
t1.setText(" ");
t2.setText(" ");
System.out.println(userName);
System.out.println(avgMark);
System.out.println(values);
}
}
}
class Student {
private String name;
private int mark;
protected String universityOne;
protected String universityTwo;
protected String universityThree;
protected boolean universityOneAccept;
protected boolean universityTwoAccept;
protected boolean universityThreeAccept;
public Student(String n, int m) {
name = n;
mark = m;
this.universityOneAccept = false;
this.universityTwoAccept = false;
this.universityThreeAccept = false;
}
public void addUniversity(String name) {
//When a university is added it doesn't mean that the user has
//accepted. So I set it to false.
this.addUniversity(name,false);
}
public void addUniversity(String name, boolean isAccepted) {
//If the user does happen to selected one university then set the isAccepted to true.
//If the user selected more than 3 universities by chance then show the message "You have chosen over 3 universities.".
if((this.universityOne == null) || (this.universityOne.equals(name))){
this.universityOne = name;
this.universityOneAccept = isAccepted;
} else if ((this.universityTwo == null) || (this.universityTwo.equals(name))) {
this.universityTwo = name;
this.universityTwoAccept = isAccepted;
} else if ((this.universityThree == null) || (this.universityThree.equals(name))) {
this.universityThree = name;
this.universityThreeAccept = isAccepted;
} else {
throw new RuntimeException("You have chosen over 3 universities.");
}
}
//Getting the marks and the name of the user and setting them.
public String getName() {
return name;
}
public int getMark() {
return mark;
}
public void setName(String name) {
this.name = name;
}
public void setMark(int mark) {
this.mark = mark;
}
//The toString() method that will print what the user's name, mark and universities chosen
//The if statements will determine whether the user has accepted or rejected.
//The ? is pretty much the alternative of the if-else statement which i learned in high-school and off internet.
//It was just easy and simple to use.
//The : tells the computer to use the value if the condition is false
//The ? tells the computer to use the value if the condition is true.
public String toString() {
String result = "Student [name=" + getName() + ",mark=" + getMark() +",universities=[";
if(this.universityOne !=null)
result += this.universityOne + ":" + (this.universityOneAccept ? "accepted" : "rejected");
if(this.universityTwo !=null)
result += this.universityTwo + ":" + (this.universityTwoAccept ? "accepted" : "rejected");
if(this.universityThree !=null)
result += this.universityThree + ":" + (this.universityThreeAccept ? "accepted" : "rejected");
result += "]]";
return result;
}
}
The HTML Code:
<html>
<applet CODE="ApplicationCentre.class" width=700 height=500>
</applet>
</html>
I know the error is on the Line 7 but I don't know how to fix it.

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.

How to get and set price from arraylist?

I am trying to get and set the price from my order form to the order summary. Will you take a look at my code and see what I am doing wrong?
My assignment requires me to use an arrayList and a JOptionPane to list out the orders and totals.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Subway extends JFrame {
private String[] breadNames = {"9-grain Wheat", "Italian", "Honey Oat", "Herbs and Cheese", "Flatbread"};
private String[] subTypes = {"Oven Roasted Chicken - $3.50", "Meatball Marinara - $4.50", "Cold Cut Combo - $4.00",
"BLT - $3.75", "Blackforest Ham - $4.00", "Veggie Delight - $2.50"};
private String[] cheesetypes = {"Cheddar", "American", "Provolone", "Pepperjack"};
private String[] size = {"6 inch", "Footlong"};
private String[] toasted = {"Yes", "No"};
private JTextField jtfname = new JTextField(10);
private JComboBox<String> jcbBread = new JComboBox<String>(breadNames);
private JComboBox<String> jcbtype = new JComboBox<String>(subTypes);
private JComboBox<String> jcbcheese = new JComboBox<String>(cheesetypes);
private JButton jbtExit = new JButton("EXIT");
private JButton jbtAnother = new JButton("Next Order");
private JButton jbtSubmit = new JButton("SUBMIT");
private JComboBox<String> jcbSize = new JComboBox<String>(size);
private JComboBox<String> jcbToasted = new JComboBox<String>(toasted);
private JCheckBox jcbLettuce = new JCheckBox("Lettuce");
private JCheckBox jcbSpinach = new JCheckBox("Spinach");
private JCheckBox jcbOnion = new JCheckBox("Onion");
private JCheckBox jcbPickles = new JCheckBox("Pickles");
private JCheckBox jcbTomatoes = new JCheckBox("Tomatoes");
private JCheckBox jcbPeppers = new JCheckBox("Peppers");
private JCheckBox jcbMayo = new JCheckBox("Mayo");
private JCheckBox jcbMustard = new JCheckBox("Mustard");
private JCheckBox jcbDressing = new JCheckBox("Italian Dressing");
public Subway() {
//name
JPanel p1 = new JPanel(new GridLayout(24, 1));
p1.add(new JLabel("Enter Name"));
p1.add(jtfname);
//size
p1.add(new JLabel("Select a size"));
p1.add(jcbSize);
//bread
p1.add(new JLabel("Select a Bread"));
p1.add(jcbBread);
//type
p1.add(new JLabel("What type of sub would you like?"));
p1.add(jcbtype);
//cheese
p1.add(new JLabel("Select a cheese"));
p1.add(jcbcheese);
//toasted
p1.add(new JLabel("Would you like it toasted?"));
p1.add(jcbToasted);
//toppings
p1.add(new JLabel("Select your toppings"));
p1.add(jcbLettuce);
p1.add(jcbSpinach);
p1.add(jcbPickles);
p1.add(jcbOnion);
p1.add(jcbTomatoes);
p1.add(jcbPeppers);
p1.add(jcbMayo);
p1.add(jcbMustard);
p1.add(jcbDressing);
// BUTTON PANEL
JPanel p5 = new JPanel();
p5.setLayout(new BoxLayout(p5, BoxLayout.LINE_AXIS));
p5.add(Box.createHorizontalGlue());// KEEPS THEM HORIZONTAL
p5.add(jbtExit);
p5.add(jbtAnother);
p5.add(jbtSubmit);
// ADDING PANELS AND WHERE THEY GO
add(p1, BorderLayout.NORTH);// TOP
add(p5, BorderLayout.SOUTH);// BOTTOM
// SETTING INVISIBLE BORDERS AROUND PANELS TO SPACE THEM OUT
p1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
p5.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// EXIT BUTTON LISTENER
jbtExit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
// Another order BUTTON LISTENER
jbtAnother.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
makeASandwich();
}
});
// SUBMIT BUTTON LISTENER
jbtSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
makeASandwich();
for (Sandwich s : Sandwich.order) {
String Order = " ";
Order = jtfname.getText() + "\n"
+ "\nSize: " + s.getSize()
+ "\nType of Sub: " + s.getName()
+ "\nBread: " + s.getBread()
+ "\nCheese: " + s.getCheese()
+ "\nToasted? " + s.getToasted() + "\nToppings: \n";
if (jcbLettuce.isSelected()) {
Order += jcbLettuce.getText();
}
if (jcbSpinach.isSelected()) {
Order += jcbSpinach.getText();
}
if (jcbPickles.isSelected()) {
Order += jcbPickles.getText();
}
if (jcbOnion.isSelected()) {
Order += jcbOnion.getText();
}
if (jcbTomatoes.isSelected()) {
Order += jcbTomatoes.getText();
}
if (jcbPeppers.isSelected()) {
Order += jcbPeppers.getText();
}
if (jcbMayo.isSelected()) {
Order += jcbMayo.getText();
}
if (jcbMustard.isSelected()) {
Order += jcbMustard.getText();
}
if (jcbDressing.isSelected()) {
Order += jcbDressing.getText();
}
Order +=
"\n Price: " + s.getPrice()
+ "\n\n---Next Order---";
JOptionPane.showMessageDialog(null, Order);
}
}
});
}
private void makeASandwich() {
double BLT_Price = 3.00;
Sandwich sandwich = new Sandwich(jcbtype.getItemAt(jcbtype.getSelectedIndex()));
sandwich.setBread(jcbBread.getItemAt(jcbBread.getSelectedIndex()));
sandwich.setCheese(jcbcheese.getItemAt(jcbcheese.getSelectedIndex()));
sandwich.setToasted(jcbToasted.getItemAt(jcbToasted.getSelectedIndex()));
sandwich.setSize(jcbSize.getItemAt(jcbSize.getSelectedIndex()));
//sandwich.setPrice(jcbtype.getItemAt(jcbtype.getSelectedIndex()));
if (jcbtype.getSelectedIndex() == 0) {
sandwich = new Sandwich(jcbtype.getItemAt(jcbtype.getSelectedIndex()), BLT_Price);
}
Sandwich.order.add(sandwich);
}
public static void main(String[] args) {
Subway frame = new Subway();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("SUBWAY");
frame.setVisible(true);
frame.setSize(600, 750);
}// ENDOFMAIN
}// ENDOFCLASS
class HoldOrder {
public static List<Sandwich> order = new ArrayList<Sandwich>();
}
class Sandwich {
String bread = "";
String sandwichName = "";
String cheese = "";
String size = "";
String toasted = "";
String lettuce = "";
private String cost = " ";
public static List<Sandwich> order = new ArrayList<Sandwich>();
public Sandwich(String typeOfSandwich, double SubPrice) {
sandwichName = typeOfSandwich;
cost += SubPrice;
}
public String getPrice() {
return cost;
}
public String getName() {
return sandwichName;
}
public void setBread(String s) {
bread = s;
}
public String getBread() {
return bread;
}
public void setCheese(String s) {
cheese = s;
}
public String getCheese() {
return cheese;
}
public void setSize(String s) {
size = s;
}
public String getSize() {
return size;
}
public void setToasted(String s) {
toasted = s;
}
public String getToasted() {
return toasted;
}
//public void setPrice(double s) {
//total = 0;
//}
//public double getPrice() {
//return total;
//}
}
This is a difficult question to answer as it will depend on portions of code you've not shared, but the basic premise will be the same...
IF the combo box of prices contains String, you will need to parse the value as a double...
Object value = jcbtype.getSelectedItem();
double price = Double.parseDouble(value);
sandwich.setPrice(price);
Beware, this will throw an NumberFormatException if the value is not parsable.
IF the combo box contains double values (which it should and then be formatted with a CellRenderer), then you might need to cast...
Object value = jcbtype.getSelectedItem();
double price = (Double)value;
sandwich.setPrice(price);
(I say might, because if you are using Java 7, you can use generics to return the base type of the JComboBox using something like double price = jcbtype.getItemAt(jcbtype.getSelectedIndex()) for example)
in the source code window of the desired class.
Right click -> Source -> Generate setters and getters ... Eclipse will generate the setter and getter methods for you.

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