I am having trouble with one part of my code. I have been working for so long on this and I am exhausted and missing something easy. I need to have a text box to enter a new title for the JFrame, a button that says "Set New Name" and an "Exit Button.
Can someone look at this code and give me some info so I can go to bed.
Thank you
//Good One
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Pool {
public static void main(String[] args) {
new poolCalc();
}
}
class poolCalc extends JFrame {
private static final long serialVersionUID = 1L;
public static final double MILLIMETER = 1;
public static final double METER = 1000 * MILLIMETER;
public static final double INCH = 25.4 * MILLIMETER;
public static final double FOOT = 304.8 * MILLIMETER;
public static final double YARD = 914.4 * MILLIMETER;
private static final DecimalFormat df = new DecimalFormat("#,##0.###");
private JTabbedPane tabs;
private JPanel generalPanel;
private JPanel optionsPanel;
private JPanel customerPanel;
private JPanel contractorPanel;
private JPanel poolPanel;
private JPanel hotTubPanel;
private JPanel tempCalPanel;
private JPanel lengthCalPanel;
public poolCalc() {
super("The Pool Calculator");
setSize(340, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
initializeComponents();
setLocationRelativeTo(null);
setVisible(true);
}
private void initializeComponents() {
Container pane = getContentPane();
tabs = new JTabbedPane();
generalTab();
optionsTab();
customerTab();
contractorTab();
poolsTab();
hotTubsTab();
tempCalTab();
lengthCalTab();
tabs.add("General", generalPanel);
tabs.add("Options", optionsPanel);
tabs.add("Customers", customerPanel);
tabs.add("Contractors", contractorPanel);
tabs.add("Pools", poolPanel);
tabs.add("Hot Tubs", hotTubPanel);
tabs.add("Temp Calc", tempCalPanel);
tabs.add("Length Calc", lengthCalPanel);
pane.add(tabs);
}
private JButton createExitButton() {
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic('x');
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return exitButton;
}
private void generalTab() {
generalPanel = new JPanel(new FlowLayout());
String currentTime = SimpleDateFormat.getInstance().format(
Calendar.getInstance().getTime());
generalPanel.add(new JLabel("Today's Date: " + currentTime));
generalPanel.add(createExitButton());
}
private JTextField createTitleField(String text, int length) {
JTextField tf = new JTextField(length);
tf.setEditable(false);
tf.setFocusable(false);
tf.setText(text);
return tf;
}
// FIX
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
private void customerTab() {
customerPanel = createContactPanel("Customer", "customer.txt");
}
private void contractorTab() {
contractorPanel = createContactPanel("Contractor", "contractor.txt");
}
private void poolsTab() {
poolPanel = new JPanel(new FlowLayout());
final JRadioButton roundPool = new JRadioButton("Round Pool");
final JRadioButton ovalPool = new JRadioButton("Oval Pool");
final JRadioButton rectangularPool = new JRadioButton("Rectangle Pool");
roundPool.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundPool);
group.add(rectangularPool);
poolPanel.add(roundPool);
poolPanel.add(rectangularPool);
poolPanel.add(new JLabel("Enter the pool's length (ft): "));
final JTextField lengthField = new JTextField(10);
poolPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the pool's width (ft): ");
widthLabel.setEnabled(false);
poolPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
poolPanel.add(widthField);
poolPanel.add(new JLabel("Enter the pool's depth (ft): "));
final JTextField depthField = new JTextField(10);
poolPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
poolPanel.add(calculateVolume);
poolPanel.add(createExitButton());
poolPanel.add(new JLabel("The pool's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
poolPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(2, 20, "");
poolPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundPool.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundPool.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
}
if (rectangularPool.isSelected()) {
volume = length * width * depth * 5.9;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener poolsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundPool) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == rectangularPool) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundPool.addActionListener(poolsListener);
ovalPool.addActionListener(poolsListener);
rectangularPool.addActionListener(poolsListener);
}
private void hotTubsTab() {
hotTubPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubPanel.add(roundTub);
hotTubPanel.add(ovalTub);
hotTubPanel.add(new JLabel("Enter the tub's length (ft): "));
final JTextField lengthField = new JTextField(10);
hotTubPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
widthLabel.setEnabled(false);
hotTubPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubPanel.add(widthField);
hotTubPanel.add(new JLabel("Enter the tub's depth (ft): "));
final JTextField depthField = new JTextField(10);
hotTubPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubPanel.add(calculateVolume);
hotTubPanel.add(createExitButton());
hotTubPanel.add(new JLabel("The tub's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"Width will be set to the same value as length");
hotTubPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0,2) * depth;
}
if (ovalTub.isSelected()) {
volume = Math.PI * ((length * width)*2) * depth;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);}
private void tempCalTab() {
tempCalPanel = new JPanel(new FlowLayout());
tempCalPanel.add(new JLabel("Enter temperature: "));
final JTextField temperatureField = new JTextField(10);
tempCalPanel.add(temperatureField);
final JComboBox optionComboBox = new JComboBox(
new String[] { "C", "F" });
tempCalPanel.add(optionComboBox);
tempCalPanel.add(new JLabel("Result: "));
final JTextField resultField = new JTextField(18);
resultField.setEditable(false);
tempCalPanel.add(resultField);
final JLabel oppositeLabel = new JLabel("F");
tempCalPanel.add(oppositeLabel);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
tempCalPanel.add(convertButton);
tempCalPanel.add(createExitButton());
final JTextArea messageArea = createMessageArea(1, 20,
"System Messages");
tempCalPanel.add(messageArea);
optionComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if ("F".equals(e.getItem())) {
oppositeLabel.setText("C");}
else {
oppositeLabel.setText("F");}}}
});
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidationResult result = validateFields(new JTextField[] { temperatureField });
String errors = "";
if (result.filled != 1 || result.valid != 1) {
errors += "Value set to zero";}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
temperatureField.setText("0");}
else {
messageArea.setVisible(false);}
double temperature = Double.parseDouble(temperatureField
.getText());
double resultValue = 0;
if (oppositeLabel.getText().equals("C")) {
resultValue = (temperature - 32.0) / 9.0 * 5.0;}
else if (oppositeLabel.getText().equals("F")) {
resultValue = ((temperature * 9.0) / 5.0) + 32.0;}
resultField.setText(df.format(resultValue));}
});
}
private void lengthCalTab() {
lengthCalPanel = new JPanel(new FlowLayout());
lengthCalPanel.add(createTitleField("Millimeters", 6));
lengthCalPanel.add(createTitleField("Meters", 4));
lengthCalPanel.add(createTitleField("Yards", 4));
lengthCalPanel.add(createTitleField("Feet", 3));
lengthCalPanel.add(createTitleField("Inches", 6));
final JTextField millimetersField = new JTextField(6);
final JTextField metersField = new JTextField(4);
final JTextField yardsField = new JTextField(4);
final JTextField feetField = new JTextField(3);
final JTextField inchesField = new JTextField(6);
lengthCalPanel.add(millimetersField);
lengthCalPanel.add(metersField);
lengthCalPanel.add(yardsField);
lengthCalPanel.add(feetField);
lengthCalPanel.add(inchesField);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double millimeters = convertToDouble(millimetersField.getText());
double meters = convertToDouble(metersField.getText());
double yards = convertToDouble(yardsField.getText());
double feet = convertToDouble(feetField.getText());
double inches = convertToDouble(inchesField.getText());
double value = 0;
if (millimeters != 0) {
value = millimeters * MILLIMETER;}
else if (meters != 0) {
value = meters * METER;}
else if (yards != 0) {
value = yards * YARD;}
else if (feet != 0) {
value = feet * FOOT;}
else if (inches != 0) {
value = inches * INCH;}
millimeters = value / MILLIMETER;
meters = value / METER;
yards = value / YARD;
feet = value / FOOT;
inches = value / INCH;
millimetersField.setText(df.format(millimeters));
metersField.setText(df.format(meters));
yardsField.setText(df.format(yards));
feetField.setText(df.format(feet));
inchesField.setText(df.format(inches));}
private double convertToDouble(String s) {
try {
return Double.parseDouble(s);}
catch (Exception e) {
return 0;}}
});
JButton clearButton = new JButton("Clear");
clearButton.setMnemonic('l');
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
millimetersField.setText(null);
metersField.setText(null);
yardsField.setText(null);
feetField.setText(null);
inchesField.setText(null);}
});
lengthCalPanel.add(convertButton);
lengthCalPanel.add(clearButton);
lengthCalPanel.add(createExitButton());}
private String loadDataFromFile(String fileName) {
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
data += reader.readLine() + "\n";}
reader.close();}
catch (IOException e){
}
return data;}
private JPanel createContactPanel(final String contactName,
final String fileName) {
JPanel pane = new JPanel(new FlowLayout());
final JTextArea customerDisplay = new JTextArea(8, 25);
customerDisplay.setLineWrap(true);
customerDisplay.setEditable(false);
pane.add(new JScrollPane(customerDisplay));
pane.add(createExitButton());
JButton addCustomerButton = new JButton("Add " + contactName);
addCustomerButton.setMnemonic('A');
pane.add(addCustomerButton);
JButton refreshButton = new JButton("Refresh");
refreshButton.setMnemonic('R');
pane.add(refreshButton);
final JTextArea messageArea = createMessageArea(2, 25, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
addCustomerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new EditContact(contactName, fileName);}
});
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = loadDataFromFile(fileName);
if (data != "") {
customerDisplay.setText(data);
customerDisplay.setEnabled(true);
messageArea.setText("File " + fileName
+ " can be read from!");
}
else {
customerDisplay.setText("Click Add "
+ contactName
+ " button to add "
+ contactName.toLowerCase()
+ ". And click Refresh button to update this pane.");
customerDisplay.setEnabled(false);
messageArea.setText("File " + fileName + " is not "
+ "there yet! It will be created "
+ "when you add " + contactName.toLowerCase()
+ "s!");
}
}
});
refreshButton.doClick();
return pane;
}
private JTextArea createMessageArea(int rows, int cols, String text) {
final JTextArea messageArea = new JTextArea(rows, cols);
messageArea.setBorder(BorderFactory.createEmptyBorder());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font("System", Font.PLAIN, 12));
messageArea.setText(text);
messageArea.setBackground(null);
messageArea.setForeground(Color.GRAY);
messageArea.setEnabled(true);
messageArea.setFocusable(false);
return messageArea;
}
private class ValidationResult {
int filled;
int valid;
}
private ValidationResult validateFields(JTextField[] fields) {
ValidationResult result = new ValidationResult();
for (int i = 0; i < fields.length; i++) {
JTextField field = fields[i];
if ((field.getText() != null) && (field.getText().length() > 0)) {
result.filled++;
}
try {
Double.parseDouble(field.getText());
field.setBackground(Color.white);
result.valid++;
}
catch (Exception e) {
field.setBackground(Color.orange);
}
}
return result;
}
private class EditContact extends JDialog {
private static final long serialVersionUID = 1L;
private final String contactName;
private final String fileName;
private File file;
private JTextField nameField;
private JTextField addressField;
private JTextField cityField;
private JComboBox stateComboBox;
private JTextField zipField;
private JTextField phoneField;
private JTextArea messageArea;
public EditContact(String contactName, String fileName) {
super(poolCalc.this, contactName + "s");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(418, 300);
this.contactName = contactName;
this.fileName = fileName;
initializeComponents();
if (openFile()) {
displayMessage(null);
}
else {
displayMessage("File " + fileName + " does not exist yet! "
+ "Will be created when you add a "
+ contactName.toLowerCase() + "!");
}
setLocationRelativeTo(null);
setVisible(true);
}
private void displayMessage(String message) {
if (message != null) {
messageArea.setVisible(true);
messageArea.setText(message);
}
else {
messageArea.setVisible(false);
}
}
private boolean openFile() {
file = new File(fileName);
return file.exists();
}
private boolean deleteFile() {
return file.exists() && file.delete();
}
private boolean saveToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,
true));
writer.write("Name: " + nameField.getText() + "\n");
writer.write("Address: " + addressField.getText() + "\n");
writer.write("City: " + cityField.getText() + "\n");
writer.write("State: "
+ stateComboBox.getSelectedItem().toString() + "\n");
writer.write("ZIP: " + zipField.getText() + "\n");
writer.write("Phone: " + phoneField.getText() + "\n");
writer.write("\n");
writer.close();
return true;
}
catch (IOException e) {
return false;
}
}
private void initializeComponents() {
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.add(new JLabel(contactName + " Name "));
nameField = new JTextField(25);
pane.add(nameField);
pane.add(new JLabel("Address "));
addressField = new JTextField(28);
pane.add(addressField);
pane.add(new JLabel("City "));
cityField = new JTextField(32);
pane.add(cityField);
pane.add(new JLabel("State "));
stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
pane.add(stateComboBox);
pane.add(new JLabel("ZIP "));
zipField = new JTextField(5);
pane.add(zipField);
pane.add(new JLabel("Phone "));
phoneField = new JTextField(10);
pane.add(phoneField);
JButton addContactButton = new JButton("Add " + this.contactName);
addContactButton.setMnemonic('A');
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveToFile()) {
displayMessage(contactName + " added");
}
else {
displayMessage("File saving error!");
}
}
});
pane.add(addContactButton);
JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
pane.add(closeButton);
JButton deleteFileButton = new JButton("Delete File");
deleteFileButton.setMnemonic('D');
deleteFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (deleteFile()) {
displayMessage("File " + fileName + " deleted!");
}
}
});
pane.add(deleteFileButton);
messageArea = createMessageArea(2, 30, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
}
}
}
Let's start with this (which I assume is where you create the details)...
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
The newTitle field is a local variable, so once the method exists, you will not be able to access the field (easily)...
You seem to have tried adding a actionListener to the newName button, which isn't a bad idea, but because you can't actually access the newTitle field, isn't going to help...
The use of setBounds is not only ill advised, but probably won't result in the results you are expecting, because the optionsPane is under the control a layout manager...
And while I was digging around, I noticed this if (errors != "") {...This is not how String comparison is done in Java. This is comparing the memory references of both Strings which will never be true, instead you should if (!"".equals(errors)) {...
But back to the problem at hand...
You are really close to having a solution. You could make the newTitle field a class instance variable, which would allow you to access the field within other parts of your program, but because you've made it final, there's something else you can try...
You can use an anonymous inner class instead...
newName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
Which should get a good nights sleep :D
It is a little unclear what you want, but if I understand you right you want the JButton newName to set the title of the JFrame to the text in some textbox?
In that case you would write
setTitle(someTextbox.getText());
inside the function of the button.
First, you need to create a JTextField that has public access. Then, create a JButton that implements ActionListener. After that you must implement the abstract method actionPerformed() in the JButton Subclass. Then in the run method say JFrame.setTitle(JTextfield.getText()).
Subclass Method:
public class main extends JFrame{
// Construct and setVisible()
}
class textfield extends JTextField{
// create field then add to JFrame
}
class button extends JButton implements ActionListener{
// create button
public void actionPerformed(ActionEvent e){
main.setTitle(textfield.getText());
}
Instance Method:
public class main implements ActionListener{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField();
JButton button = new JButtone();
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
public void actionPerformed(ActionEvent e){
frame.setTitle(field.getText);
}
}
Try This
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
// optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
// newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
Related
I am trying to use a JButton based keyboard in a GUI based game of Hangman. However when I want to check that the key pressed is in the hidden word, I am not sure where I need to change the type from String to char. I want to use the GUI based keyboard instead of allowing the user to use the keyboard, to try and minimise the validation that needs to be done. These are the classes that I have created thus far. I am struggling to get this working.
package guis;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MouseClick extends JFrame implements ActionListener, MouseListener
{
private static final long serialVersionUID = 1L;
private static ActionListener letterHandler = null;
private Container cPane;
private JLabel lblTitle, lblTries, lblCountryToGuess, chancesLabel, message;//, usedLettersPanel;
private JButton btnExit, btnStart, btn1, btn3, btn4, btnX;
private JButton [] btn = new JButton[26];
private JPanel pNorth, pSouth, pEast, pWest, pCenter, wordPanel, messagePanel, usedLettersPanel, hangPanel, drawingFrame;//, lblCountryToGuess;
private JMenuItem mIRules, mIDev, mIRestart, mIExit;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JPopupMenu.Separator jSeparator1;
private JFrame frame = new JFrame();
private JButton enter;
private JLabel[] wordArray, usedLetters;
//private JFrame drawingFrame;
private HangmanDrawing drawing;
private char[] incorrectGuesses;
private char[] buttonLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private String word;
private int chances;
char input;
private JFrame endFrame;
private JPanel top, bottom;
private JLabel doNow;
private JButton restart, exit;
MouseClick() throws IOException
{
super("Assignment 2 - Hangman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
word = new WordHandler().getRandomWord();
chances = 7;
cPane = getContentPane();
cPane.setBackground(new Color (236, 128, 19));
pNorth = new JPanel();
pSouth = new JPanel();
pEast = new JPanel();
pWest = new JPanel();
pCenter = new JPanel();
lblTitle = new JLabel(" Hangman ", SwingConstants.CENTER);
lblTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
lblTitle.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle.setBackground(new Color (38, 29, 226));
lblTitle.setOpaque(true);
lblTitle.setForeground(Color.white);
pNorth.add(lblTitle);
/*lblCountryToGuess = new JLabel("", SwingConstants.CENTER);
lblCountryToGuess.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
//lblCountryToGuess.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
lblCountryToGuess.setBounds(50, 1, 500, 60);
lblCountryToGuess.setBorder(BorderFactory.createTitledBorder("This is the country to be guessed..."));
//wordArray = new JLabel [hiddenCountry.length()];
//for (int i = 0 ; i < wordArray.length ; i++)
//{
// wordArray[i] = new JLabel("_");
// wordArray[i].setFont(new Font("Comic Sans MS.", Font.BOLD, 23));
// lblTitle4.add(wordArray[i]);
//}
pCenter.add(lblCountryToGuess);*/
hangPanel = new HangmanDrawing();
//drawing = new HangmanDrawing();
drawingFrame = new JPanel();
//drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//drawingFrame.setFocusableWindowState(false);
//drawingFrame.getContentPane().add(drawing);
//int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
//drawingFrame.setSize(scrnsize.width - xPosition - 10,
//scrnsize.width - xPosition - 10);
// drawingFrame.setLocation(xPosition,
//(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);
pCenter.add(drawingFrame);
wordPanel = new JPanel();
wordPanel.setBounds(100, 100, 100, 60);
wordPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
wordPanel.setBorder(BorderFactory.createTitledBorder("This is the country to guess..."));
wordArray = new JLabel [word.length()];
for (int i = 0 ; i < wordArray.length ; i++)
{
wordArray[i] = new JLabel("_");
wordArray[i].setFont(new Font("Arial", Font.BOLD, 23));
wordPanel.add(wordArray[i]);
}
pCenter.add(wordPanel);
usedLettersPanel = new JPanel();
usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
incorrectGuesses = new char [chances];
usedLetters = new JLabel [incorrectGuesses.length];
for (int i = 0 ; i < usedLetters.length ; i++)
{
usedLetters[i] = new JLabel("~");
usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
usedLettersPanel.add(usedLetters[i]);
}
pCenter.add(usedLettersPanel);
messagePanel = new JPanel();
messagePanel.setLayout (new FlowLayout (FlowLayout.LEFT));
message = new JLabel ("Guess a letter...");
message.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
messagePanel.add(message);
pCenter.add(messagePanel);
/*usedLettersPanel = new JLabel();
usedLettersPanel.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
usedLettersPanel.setBounds(50, 1, 500, 60);
usedLettersPanel.setBorder(BorderFactory.createTitledBorder("Letters already guessed..."));
//usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
//incorrectGuesses = new char [chances];
//usedLetters = new JLabel [incorrectGuesses.length];
//for (int i = 0 ; i < usedLetters.length ; i++)
//{
//usedLetters[i] = new JLabel("~");
//usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
//usedLettersPanel.add(usedLetters[i]);
//}
pCenter.add(usedLettersPanel);*/
btnStart = new JButton(" Start / New Game ");
btnStart.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnStart.setBackground(Color.GREEN);
btnStart.setForeground(Color.white);
btnStart.setOpaque(true);
btnStart.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnStart);
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
chancesLabel = new JLabel (chances + " chances left...");
chancesLabel.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
//lblTries = new JLabel(" Tries Remaining ");
//lblTries.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
chancesLabel.setBackground(new Color (38, 29, 226));
chancesLabel.setForeground(Color.white);
chancesLabel.setOpaque(true);
chancesLabel.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(chancesLabel);
btnExit = new JButton(" Exit Game");
btnExit.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnExit.setBackground(new Color (236, 19, 35));
btnExit.setForeground(Color.white);
btnExit.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnExit);
for(int i = 0; i < 26; i++)
{
//JButton btnX = new JButton();
btnX = new JButton(new KeyboardListener(buttonLetters[i]));
btnX.setText("" + buttonLetters[i]);
pSouth.add(btnX);
btnX.setVisible(true);
//btn[i] = btnX;
//btn[i].setText("" + (char)('A'+ i));
//btn[i].setText("" + buttonLetters[i]);
//input = buttonLetters[i];
//pSouth.add(btn[i]);
//btn[i].setVisible(true);
}
cPane.add(pNorth, BorderLayout.NORTH);
cPane.add(pSouth, BorderLayout.SOUTH);
pSouth.setLayout(new GridLayout(3,10,1,1));
cPane.add(pWest, BorderLayout.WEST);
pWest.setLayout(new GridLayout(3,1,1,10));
cPane.add(pEast, BorderLayout.EAST);
cPane.add(pCenter, BorderLayout.CENTER);
pCenter.setLayout(new GridLayout(4, 1, 1, 1));
/*Container chancesContainer = new Container();
chancesContainer.setLayout(new FlowLayout (FlowLayout.RIGHT));
chancesContainer.add(chancesLabel);
JPanel wrongGuessesContainer = new JPanel();
wrongGuessesContainer.setLayout(new GridLayout (1, 2));
wrongGuessesContainer.setBorder(BorderFactory.createTitledBorder ("Wrong Guesses"));
wrongGuessesContainer.add(usedLettersPanel);
wrongGuessesContainer.add (chancesContainer);
Container bottomContainer = new Container();
bottomContainer.setLayout(new BorderLayout());
bottomContainer.add(wrongGuessesContainer, BorderLayout.NORTH);
bottomContainer.add(messagePanel, BorderLayout.SOUTH);
getContentPane().setLayout(new BorderLayout());
//getContentPane().add (inputPanel, BorderLayout.NORTH);
getContentPane().add(wordPanel, BorderLayout.CENTER);
getContentPane().add(bottomContainer, BorderLayout.SOUTH);*/
btnExit.addActionListener(this);
pCenter.addMouseListener(this);
pNorth.addMouseListener(this);
pSouth.addMouseListener(this);
pEast.addMouseListener(this);
pWest.addMouseListener(this);
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("New Game");
jMenuItem1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Help");
jMenuItem3.setText("Rules");
jMenuItem3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Hangman is a guessing game where the word"
+"\n to guess is represented by dashes. The player"
+"\n is given the option to enter a letter. If the letter"
+"\n guessed is contained in the word, the letter will"
+"\n replace the dash in its approprate placement."
+"\n You cannot exceed 7 wrong guesses or else you"
+"\n lose. Words are selected randomly.", "Instructions",
JOptionPane.INFORMATION_MESSAGE);
}
});
jMenu2.add(jMenuItem3);
jMenu2.add(jSeparator1);
jMenuItem4.setText("Developer");
jMenuItem4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Developer: Ryan Smith");
}
});
jMenu2.add(jMenuItem4);
jMenuBar1.add(jMenu2);
jMenu3.setText("Exit");
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItem5.setText("Exit Game");
jMenuItem5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
jMenu3.add(jMenuItem5);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
pack();
/*drawing = new HangmanDrawing();
drawingFrame = new JFrame();
drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
drawingFrame.setFocusableWindowState(false);
drawingFrame.getContentPane().add(drawing);
int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
drawingFrame.setSize(scrnsize.width - xPosition - 10,
scrnsize.width - xPosition - 10);
drawingFrame.setLocation(xPosition,
(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);*/
}
private void endGame()
{
enter.removeActionListener (this);
//inputField.removeActionListener(this);
//inputField.setEditable (false);
endFrame = new JFrame();
top = new JPanel();
bottom = new JPanel();
doNow = new JLabel ("What do you want to do now?");
restart = new JButton ("Start Again");
exit = new JButton ("Exit Hangman");
doNow.setFont (new Font ("Verdana", Font.BOLD, 17));
top.setLayout (new FlowLayout (FlowLayout.CENTER));
top.add (doNow);
restart.setFont (new Font ("Arial", Font.BOLD, 12));
restart.addActionListener(this);
exit.setFont (new Font ("Arial", Font.BOLD, 12));
exit.addActionListener(this);
bottom.setLayout (new FlowLayout (FlowLayout.CENTER, 44, 10));
bottom.add (restart);
bottom.add (exit);
endFrame.getContentPane().setLayout (new BorderLayout());
endFrame.getContentPane().add (top, BorderLayout.NORTH);
endFrame.getContentPane().add (bottom, BorderLayout.SOUTH);
endFrame.pack();
Dimension scrnsize = Toolkit.getDefaultToolkit().getScreenSize();
endFrame.setLocation ((int) (scrnsize.width - endFrame.getWidth())/2,
(int) (scrnsize.height - this.getHeight())/3 + this.getHeight());
endFrame.setResizable (false);
endFrame.setVisible (true);
this.setFocusableWindowState(false);
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource().equals(btnExit))
{
System.exit(0);
}
else if (event.getSource().equals(restart))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
//new HangmanMenu();
}
else if (event.getSource().equals(exit))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
System.exit(0);
}
else
{
try
{
//char input = Character.toUpperCase(inputField.getText().charAt(0));
//if(event.getSource().equals(btn))
//{
//System.out.println("\n" + input);
boolean letterInWord = false;
for (int i = 0 ; i < word.length() ; i++)
{
if (word.charAt (i) == input)
{
letterInWord = true;
break;
}
}
if (!letterInWord) {
boolean alreadyGuessed = false;
for (int i = 0 ; i < incorrectGuesses.length ; i++) {
if (incorrectGuesses [i] == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
chances--;
drawing.addPart();
if (chances >= 0) {
incorrectGuesses [incorrectGuesses.length - chances - 1] = input;
usedLetters [usedLetters.length - chances - 1].setText ("" + input);
message.setText ("Woops, wrong! Try again!");
chancesLabel.setText (chances + " chances left...");
} else {
chancesLabel.setText ("Sorry, you lose.");
message.setText ("The word was: " + word);
endGame();
}
}
} else {
boolean alreadyGuessed = false;
for (int i = 0 ; i < wordArray.length ; i++) {
if (wordArray [i].getText().charAt (0) == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
for (int i = 0 ; i < word.length() ; i++) {
if (word.charAt (i) == input) {
wordArray [i].setText ("" + input);
}
}
boolean wordComplete = true;
for (int i = 0 ; i < wordArray.length ; i++) {
if (!Character.isLetter (wordArray [i].getText().charAt (0))) {
wordComplete = false;
break;
}
}
if (!wordComplete) {
message.setText ("Well done, you guessed right!");
} else {
message.setText ("Congratulations, you win the game!");
drawing.escape();
endGame();
}
}
//}
}
//inputField.setText ("");
}catch (Exception x)
{
}
}
}
#Override
public void mouseClicked(MouseEvent e){}
#Override
public void mouseEntered(MouseEvent e){}
#Override
public void mouseExited(MouseEvent e){}
#Override
public void mousePressed(MouseEvent e){}
#Override
public void mouseReleased(MouseEvent e){}
class KeyboardListener implements ActionListener
{
private final char letter;
public KeyboardListener(char letter)
{
this.letter = letter;
}
public char getLetter()
{
return letter;
}
#Override
public void actionPerformed(ActionEvent e)
{
char tempLetter;
if (e.getSource().equals(btnX))
{
tempLetter = 'A';
}
}
}
}
This is the code for the WordHandler class.
package guis;
import java.io.*;
class WordHandler
{
private BufferedReader fileIn;
private String[] wordArray;
private File wordFile;
public WordHandler() throws IOException
{
wordFile = new File("countriesnospaces.txt");
int arrayCounter = 0;
try {
BufferedReader fileIn = new BufferedReader(new FileReader(wordFile));
while (fileIn.readLine() != null)
{
arrayCounter++;
}
wordArray = new String [arrayCounter];
fileIn.close();
fileIn = new BufferedReader(new FileReader(wordFile));
for (int pos = 0 ; pos < arrayCounter ; pos++)
{
wordArray[pos] = fileIn.readLine();
}
fileIn.close();
} catch (FileNotFoundException e)
{
System.out.println("File not found. Please create it and add words.");
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
public String getRandomWord() throws IOException
{
int random = (int) (Math.random() * wordArray.length);
return wordArray[random].toUpperCase();
}
public void sort()
{
String temp;
for (int loop = 0 ; loop < wordArray.length - 1 ; loop++) {
for (int pos = 0 ; pos < wordArray.length - 1 - loop ; pos++) {
if (wordArray[pos].compareTo(wordArray[pos + 1]) >0) {
temp = wordArray[pos];
wordArray[pos] = wordArray[pos + 1];
wordArray[pos + 1] = temp;
}
}
}
}
public String[] getArray()
{
return wordArray;
}
}
This is the test class.
package guis;
import java.io.IOException;
import javax.swing.JFrame;
public class TestMouseClick
{
public static void main(String[] args) throws IOException
{
MouseClick sample = new MouseClick();
sample.setTitle("Assignment 2 - Hangman");
sample.setSize(800, 750);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}
}
A simple fix would be getting the first character in the String returned by JButton tooltip text using the charAt(0) method and assign it to input:
char input = jButton26.getToolTipText().charAt(0);
or you could split it up to make it clearer:
String s = jButton26.getToolTipText();
char input = s.charAt(0);
Also just a tip, instead of manually coding each individual JButton for the GUI keyboard, you could create an array containing all 26 letters and then create the buttons and attach listeners using a for loop. This would significantly reduce the amount of code you have to write.
New Edit: creating and setting up lots of similar objects
(Also I noticed you created an array to store the buttons as well as a buttonLettersarray - this isn't necessary unless you have changed your code to utlise an array of buttons)
The important thing to note here is that ActionListener is an object in Java so it can be defined to store data and other method definitions like any other class. Personally I would prefer to write an inner class that extends ActionListener to store the letter that each button represents.
//define this inner class outside of the methods
class KeyboardListener extends ActionListener {
//field type depends on your buttonLetters array (not sure if it is chars or Strings)
private final String letter;
public KeyboardListener(String letter) {
this.letter = letter;
}
public String getLetter() {
return letter;
}
#Override
public void actionPerformed(ActionEvent ae) {
//do something when button is clicked
//you can make use of the getLetter() method to retrieve the letter
}
}
//this goes in the for loop when creating each button
JButton btnX = new JButton(new KeyboardListener(buttonLetters[i]));
//add button to interface and anything else
Note: one of the JButton constructors can take any class that implements the Action interface (or extends ActionListener in this case) to add it upon creation rather than having to call addActionListener().
I'm trying to save data from a GUI I made, to a text document. In the GUI I have a menubar with a menu for opening and saving. they both work just fine. the problem is with the finish button. The finish button has to save to a text document without that popup box showing (without this
https://gyazo.com/41fd2370025c7c49cb375c0f64936597).
It has to save in the background without the user having to click "ok" or "save" in my case. It has to save automatically basically. Here is my code:
public class Survey extends JFrame {
public JLabel label;
public JLabel age;
JPanel panel = new JPanel();
JComboBox<String> majorsList;
JTextField textField;
JRadioButton Male;
JRadioButton Female;
JCheckBox workButton;
JCheckBox homeButton;
JCheckBox pcButton;
Integer ageInfo;
int hasJob;
int isHome;
int hasPC;
int age1;
int workAns;
int homeAns;
int PCAns;
String majorsInfo;
String rbinfoMale;
String rbinfoFemale;
String sex;
File fileToSave;
String file_name;
String My_File;
JPanel rButton;
ButtonGroup bg1;
JFileChooser fileChooser;
File fileToOpen;
StringBuilder sb;
String fullcombo;
JFrame parentFrame;
JMenuItem openItem;
JMenuItem saveItem;
File file;
ArrayList<String> allInputs = new ArrayList<String>();
public Survey() {
fileChooser = new JFileChooser();
//JTextField textfield = new JTextField();
//textfield.add(textfield(), BorderLayout.NORTH);
JPanel finishButton = new JPanel();
finishButton.add(finish());
JPanel northPanel = new JPanel();
northPanel.add(age());
JPanel centerPanel = new JPanel();
centerPanel.add(Majors());
centerPanel.add(RadioButtons());
centerPanel.add(locationWork());
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(createFileMenu());
menuBar.add(createDrawMenu());
//ageInput.add(createTextField());
//createTextField();
//textField = new JTextField(10);
//textField.setBounds(5, 5, 280, 50);
//panel.add(textField, BorderLayout.NORTH);
add(northPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
add(finishButton, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
}
public static void main(String args[]) {
Survey c = new Survey();
c.setTitle("Survey");
c.setVisible(true);
}
public JMenu createFileMenu() {
JMenu menu = new JMenu("File");
saveItem = new JMenuItem("Save");
openItem = new JMenuItem("Open");
JMenuItem quitItem = new JMenuItem("Quit");
ActionListener listener = new ExitItemListener();
quitItem.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
saveItem.addActionListener(listener2);
ActionListener listener3 = new OpenItemListener();
openItem.addActionListener(listener3);
menu.add(saveItem);
menu.add(openItem);
menu.add(quitItem);
return menu;
}
public JMenu createDrawMenu() {
JMenu menu = new JMenu("Draw");
saveItem = new JMenuItem("Save");
openItem = new JMenuItem("Open");
JMenuItem quitItem = new JMenuItem("Quit");
ActionListener listener = new ExitItemListener();
quitItem.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
saveItem.addActionListener(listener2);
menu.add(saveItem);
menu.add(openItem);
menu.add(quitItem);
return menu;
}
public JPanel finish() {
JButton finish = new JButton("Finish");
panel.add(finish);
ActionListener listener = new ExitItemListener();
finish.addActionListener(listener);
ActionListener listener2 = new SaveItemListener();
finish.addActionListener(listener2);
return panel;
}
public JPanel age() {
JPanel textf = new JPanel();
textf.add(age = new JLabel("Age: "));
textField = new JTextField(10);
textField.setBounds(5, 5, 280, 50);
textField.setFont(textField.getFont().deriveFont(20f));
textf.setBorder(new BevelBorder(0));
textf.add(textField);
return textf;
}
public JPanel Majors() {
JPanel majorPanel = new JPanel();
String[] majorsStrings = {"Biology", "Chemistry", "Computer Science", "Engineering"};
majorsList = new JComboBox<String>(majorsStrings);
majorsList.setBorder(new TitledBorder(new EtchedBorder(), "College"));
majorsList.setSelectedIndex(3);
majorsList.addActionListener(majorsList);
majorPanel.add(majorsList);
return majorPanel;
}
public JPanel RadioButtons() {
bg1 = new ButtonGroup();
rButton = new JPanel();
Male = new JRadioButton("Male");
Female = new JRadioButton("Female");
rButton.setLayout(new GridLayout(2, 1));
bg1.add(Male);
bg1.add(Female);
rButton.add(Male);
rButton.add(Female);
return rButton;
}
public JPanel locationWork() {
workButton = new JCheckBox("Work");
homeButton = new JCheckBox("Have Children");
pcButton = new JCheckBox("Own PC");
JPanel cButton = new JPanel();
workButton.setMnemonic(KeyEvent.VK_C);
homeButton.setMnemonic(KeyEvent.VK_G);
pcButton.setMnemonic(KeyEvent.VK_H);
cButton.setLayout(new GridLayout(3, 1));
cButton.add(workButton);
cButton.add(homeButton);
cButton.add(pcButton);
return cButton;
}
private String inputCombo(int age1, String major, String sex, int work, int kids, int comp) {
String newAge = Integer.toString(age1);
String hasWork = Integer.toString(work);
String hasKids = Integer.toString(kids);
String hasComp = Integer.toString(comp);
String combo = major + ", " + newAge + ", " + sex + ", " + hasWork + ", " + hasKids + ", " + hasComp;
return combo;
}
private ArrayList<String> inputData() {
boolean catcher = true;
try {
age1 = Integer.parseInt(textField.getText());
} catch (IllegalFormatException ex) {
catcher = false;
System.out.println("Not an integer");
}
majorsInfo = majorsList.getSelectedItem().toString();
if (Male.isSelected()) {
sex = "Male";
} else if (Female.isSelected()) {
sex = "Female";
} else {
sex = "";
catcher = false;
}
if (workButton.isSelected()) {
workAns = 1;
} else {
workAns = 0;
}
if (homeButton.isSelected()) {
homeAns = 1;
} else {
homeAns = 0;
}
if (pcButton.isSelected()) {
PCAns = 1;
} else {
PCAns = 0;
}
if (catcher) {
fullcombo = inputCombo(age1, majorsInfo, sex, workAns, homeAns, PCAns);
allInputs.add(fullcombo);
} else {
System.out.println("Fill out all fields please");
}
return allInputs;
}
class ExitItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
class SaveItemListener implements ActionListener {
public void actionPerformed(ActionEvent event1) {
try {
fileChooser.showSaveDialog(Survey.this);
if (fileChooser.showSaveDialog(Survey.this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
StringBuilder sb = new StringBuilder();
FileWriter fw = new FileWriter(file, true);
for (String a : inputData()) {
sb.append(a);
sb.append("\r\n");
}
fw.write(sb.toString());
fw.flush();
fw.close();
}
} catch (IOException ex) {
}
}
}
class OpenItemListener implements ActionListener {
public void actionPerformed(ActionEvent event2) {
File file = fileChooser.getSelectedFile();
fileChooser.showOpenDialog(Survey.this);
}
}
}
I have a Swing Form (Java). In this form I have field, for example Name1. I initialize it so:
private JTextField Name1;
In this code i'm adding JTextField Name1 into my Form:
tabbedPane.addTab("T6", null, panel, "T6");
panel.setLayout(null);
Name1.setBounds(73, 11, 674, 20);
panel.add(Name1);
Additionaly I have Button1 on my form. The event in this button is changing the value of Name1. Its work normaly.
Moreover I have a Button 2 that hiding the Tab with Name1:
tabbedPane.remove(1);
tabbedPane.repaint();
tabbedPane.revalidate();
frame.repaint();
frame.revalidate();
(And, of course, I turn on my tabpane again after this)
After all that, by the pressing the Button 4 I want to change the vlue of Name1 to some text.
But it doesn't work!!!!!! SetTex doesnt work. The field is empty.
So, if I change the Name1 declaration from
private JTextField Name1;
to
static JTextField Name1;
Yes, it works. BUT! Then I can't change the value of Name1 by using
Name1.Settext("Example");
What i have to do to make Name1 available after Button 4 pressed and changable ????
The all code is:
public class GUI {
public JTextField Name_textField;
public static void main(String[] args) {
DB_Initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setResizable(false);
FirstConnect FC = window.new FirstConnect();
ConnectStatus = true;
FC.FirstEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
CurrentEnty_textField = new JTextField();
Name_textField = new JTextField();
EntriesCountlbl = new JLabel("New label");
initialize();
EntriesCountlbl.setText(Integer.toString(EC1));
if (LoginStatus == true) {
System.out.println("LoginStatus == true");
AdminPartOn();
btnNewButton.setEnabled(false);
} else {
btnNewButton_3.setEnabled(false);
tabbedPane.setEnabledAt(1, false);
// UnableForm();
AdminPartOff();
}
}
public static void DB_Initialize() {
conn3 = con3.DoConnect();
int ID;
ArrayList<String> list = new ArrayList<String>();
String l;
String p;
list = con3.LoginFileRead();
if (list.size() == 2) {
l = list.get(0);
p = list.get(1);
System.out.println("Логин из файла = " + l);
System.out.println("Пароль из файла = " + p);
ID = con3.CRMUserRequest(conn3, l, p);
AdminPanelData = con3.CRMUserFullData(conn3, l, p);
if (ID != 0) {
System.out.println("ID Юзера = " + ID);
LoginStatus = true;
}
}
EC1 = con3.CRMQuery_EntriesCount(conn3); // запрашиваем кол-во записей
StatusTableEntriesCount = con3.CRMQueryStatus_EntriesCount(conn3);
StatusTableFromCount = con3.CRMQueryFRom_EntriesCount(conn3);
System.out.println("Entries count(Из модуля GYU): " + EC1);
if (EC1 > 0) {
CurrentEntry = 1;
System.out.println("Все ОК, текущая запись - " + CurrentEntry);
} else {
System.out.println("Выскакивает обработчик ошибок");
}
con3.Ini();
con3.CRMQuery2(conn3, EC1 + 1);
StatusColumn = con3.CRMQueryStatus(conn3, StatusTableEntriesCount);
FromColumn = con3.CRMQueryFrom(conn3, StatusTableFromCount);
}
public class FirstConnect {
public void FirstEntry() {
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
if (LoginStatus != false) {
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
Name_textField.setText("-");
}
}
}
private void initialize() {
frame = new JFrame();
panel = new JPanel();
frame.setBounds(100, 100, 816, 649);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 250, 780, 361);
frame.getContentPane().add(tabbedPane);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("\u0412\u0445\u043E\u0434", null, panel_1, null);
btnNewButton = new JButton("\u0412\u0445\u043E\u0434");
btnNewButton.setBounds(263, 285, 226, 37);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ID;
ID = con3.CRMUserRequest(conn3, LoginField.getText(), PasswordField.getText());
if (ID == 0) {
} else {
MainTab();
FirstEntry3();
}
}
});
panel_1.setLayout(null);
panel_1.add(btnNewButton);
tabbedPane.addTab("\u041A\u043B\u0438\u0435\u043D\u0442", null, panel,
"\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u0430");
panel.setLayout(null);
// Name_textField = new JTextField();
Name_textField.setBounds(73, 11, 674, 20);
panel.add(Name_textField);
Name_textField.setHorizontalAlignment(SwingConstants.CENTER);
Name_textField.setColumns(10);
NextEntryButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (NextEntryButton.isEnabled() != false) {
if (CurrentEntry < EC1) {
CurrentEntry = CurrentEntry + 1;
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
}
}
}
});
}
public void MainTab() {
tabbedPane.addTab("1", null, panel,
"1");
tabbedPane.setEnabledAt(1, true);
panel.setLayout(null);
}
public void FirstEntry3() {
Name_textField.setText(F.GetName(CurrentEntry - 1));
}
}
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 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.