I have to write a Java code where I should get input from 2 different combo boxes. The input, that I will get, has to be display in a text field. I have written a part of my code but I can't get the input.
This is what I have written so far:
package main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboI extends JFrame implements ItemListener{
JComboBox dita = new JComboBox();
JComboBox ora = new JComboBox();
JLabel dita1 = new JLabel("Zgjidhni diten:");
JLabel ora1 = new JLabel("Zgjidhni oren");
JTextArea pergjigje = new JTextArea(2, 10);
public ComboI(){
super("Orari mesimor IE102");
setSize(600, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container content = getContentPane();
FlowLayout lay = new FlowLayout(FlowLayout.LEFT);
content.setLayout(lay);
content.add(dita);
content.add(dita1);
content.add(ora1);
content.add(ora);
content.add(pergjigje);
setContentPane(content);
dita.addItem("E Hene");
dita.addItem("E Marte");
dita.addItem("E Merkure");
dita.addItem("E Enjte");
dita.addItem("E Premte");
dita.addItemListener(this);
ora.addItem("08:30 - 09:25");
ora.addItem("09:30 - 10:25");
ora.addItem("10:30 - 11:25");
ora.addItem("11:30 - 12:25");
ora.addItem("12:30 - 13:25");
ora.addItem("13:30 - 14:25");
ora.addItemListener(this);
}
public void itemStateChanged(ItemEvent event){
String choice1 = event.getItem().toString();
String choice2 = event.getItem().toString();
if (choice1.equals("E Marte") && choice2.equals("E Marte")){
String a = "hi";
pergjigje.setText(a);
}
}
}
String choice1 = event.getItem().toString();
String choice2 = event.getItem().toString();
You can only generate an event for one combo box at a time, so if you want the values from the combo boxes you need to access the combo box, not the event.
The code would be something like:
String choice1 = dita.getSelectedItem().toString();
String choice2 = ora.getSelectedItem().toString();
You can use the getSelectedItem() method, with a cast to String. Or, you can use getItemAt with getSelectedIndex and a generic JComboBox<String> for your fields - this has the advantage of compile time type safety, and not needing a cast.
String sd = (String)dita.getSelectedItem();
String so = (String)ora.getSelectedItem();
or
String sd = dita.getItemAt(dita.getSelectedIndex());
String so = ora.getItemAt(ora.getSelectedIndex());
The other advantage of the second approach is that you can instead use getSelectedIndex to get a day of the week, or a time slot, from an array without having to parse text. For example:
// using java 8 for the java.time.DayOfWeek enum
DayOfWeek day = DayOfWeek.of(dita.getSelectedIndex());
// simply storing the hour of the time selection
int hour = ora.getSelectedIndex();
// using joda time for time without dates
// with org.joda.time.LocalTime
LocalTime time = new LocalTime(ora.getSelectedIndex() + 7, 30);
Detecting when the user hasn't made a selection
You should also be aware that, for your code, even if the user has not yet selected an item it will return the first item in the combobox. You may therefore want to add a "choose an item ..." string before any of the other entries. For example:
dita.addItem("Select a day ...");
dita.addItem("E Hene");
...
// inside the listener
if (dita.getSelectedIndex() == 1) { // no choice made yet }
Related
I know that it is possible in an event driven program in Java to find out what object caused an event (e.g. JRadioButton was selected, therefore a certain action will take place). My question is, if you have 2 JRadioButtons in a buttongroup, both with action listeners added to them, and you keep selecting from one to the other, is it possible to find out what JRadioButton was previously selected? In other words, if I selected another JRadioButton, is it possible to write code that determines which JRadioButton was previously selected before selecting the current JRadioButton?
public class Drinks extends JPanel implements ActionListener{
double drinksPrice = 2.10;
double noDrinks = 0;
static String selectedDrink;
JRadioButton btnPepsi = new JRadioButton("Pepsi"); //add a button to choose different drinks
JRadioButton btnMtDew = new JRadioButton("Mt Dew");
JRadioButton btnDietPepsi= new JRadioButton("Diet Pepsi");
JRadioButton btnCoffee = new JRadioButton("Coffee");
JRadioButton btnTea = new JRadioButton("Tea");
JRadioButton btnNone = new JRadioButton("None");
JLabel lblDrinksHeading = new JLabel("Choose a drink (each drink is $2.10):");
ButtonGroup drinksButtonGroup = new ButtonGroup();
private static final long serialVersionUID = 1L;
public Drinks(){
setLayout(new FlowLayout()); //Using GridLayout
btnPepsi.setActionCommand(btnPepsi.getText()); //set the ActionCommand to getText so I can retrieve the name for the receipt
btnMtDew.setActionCommand(btnMtDew.getText());
btnDietPepsi.setActionCommand(btnDietPepsi.getText());
btnCoffee.setActionCommand(btnCoffee.getText());
btnTea.setActionCommand(btnTea.getText());
btnNone.setActionCommand(btnNone.getText());
drinksButtonGroup.add(btnPepsi);
drinksButtonGroup.add(btnMtDew);
drinksButtonGroup.add(btnDietPepsi);
drinksButtonGroup.add(btnCoffee);
drinksButtonGroup.add(btnTea);
drinksButtonGroup.add(btnNone);
btnNone.setSelected(true); //set default to "none"
btnPepsi.addActionListener(this);
btnMtDew.addActionListener(this);
btnDietPepsi.addActionListener(this);
btnCoffee.addActionListener(this);
btnTea.addActionListener(this);
btnNone.addActionListener(this);
add(lblDrinksHeading);
add(btnPepsi);
add(btnDietPepsi);
add(btnMtDew);
add(btnCoffee);
add(btnTea);
add(btnNone);
repaint();
revalidate();
selectedDrink = drinksButtonGroup.getSelection().getActionCommand();
//add the drink price to totalPrice, it is adding it every time though, even if its none
/*if(drinksButtonGroup.getSelection() == btnNone){
MenuFrame.totalPrice += 0;
}
else{
MenuFrame.totalPrice += drinksPrice;
}
*/
// buttonGroup1.getSelection().getActionCommand()
//String selectedDrink = drinksButtonGroup.getSelection().toString();
//class
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == btnNone) {
MenuFrame.totalPrice += 0;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
else {
MenuFrame.totalPrice += drinksPrice;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
}
Edit: I'll be more specific. I am creating an "imaginary" restaurant program. In it, I list several drinks that have the same price (e.g. Pepsi: $2.10, Mountain Due: $2.10, etc). These listed drinks are JRadioButtons. Once a customer clicks one of these buttons to "order a drink", $2.10 will be added to a "total" variable. However, a problem occurs when a user wants to change there drink, because if they click a different JRadioButton, $2.10 will still be added to the "total" variable. I want to make it so that they can change there drink without adding $2.10 to the order every time.
I think the problem is at this line:
MenuFrame.totalPrice += drinksPrice;
Because "+=" increments a value by another value instead of simply adding two values.
So every time the user clicks on one of the radio buttons, it will continuously add 2.10 to your total value, whereas if you were you just say:
MenuFrame.totalPrice = MenuFrame.totalPrice + drinksPrice;
It will set your total price equal to the current total price plus the price of drinks, instead of adding 2.10 to the total value every time a button is pressed.
Perhaps I am misunderstanding the question, but I am thinking along the lines of creating a public variable, and then inside the action listeners updating the variable with the radio button that was just selected. When the selected event fires, you can look at the variable to see which radio button had last been selected, do what you want to about it, and then update it with the new radio button.
I am trying to implement a recurrent addition calculation. This should get the current quantity (from the Quantity textfield) and the saved quantity (total quantity to be saved), outputting the total result below the 'Results' heading. View of tabbed page for calculation.
I have tried the following code, but it contains errors and uses a Dialog to output the result (which is not what I want).
addItem.addComponent(selectItem);
TextField quantity = new TextField("", "Quantity (ml or g)", 4, TextArea.NUMERIC);
addItem.addComponent(quantity);
Button add = new Button("Add");
addItem.addComponent(add);
TextArea results = new TextArea("Results");
addItem.addComponent(results);
//TextArea total = new TextArea("Add Item");
//addItem.addComponent(total);
//--------------------------------------------------------------
add.addActionListener((ActionEvent ev) -> {
Storage s = Storage.getInstance();
Integer addition = 0;
// Read my "Hello World" string back from storage
addition = (Integer)s.readObject("total");
int d = Int.parseInt(quantity.getText());
Integer total = addition + quantity;
// Save the "Hello World" string to storage
s.writeObject("total", total);
Dialog.show("", total, "OK", "Cancel");
});
//--------------------------------------------------------------
return addItem;
I would therefore appreciate any advice and guidance on how this could be implemented in my code.
To present it in a table , you can use easily GridLayout in this way :
Container ctrResultTable = new Container(new GridLayout(1,3));
//Define a new container associated to a gridlayout with 1 row and 1 column
ctrResult.addComponent(new Label(d.toString()));
ctrResult.addComponent(new Label(total.toString()));
ctrResult.addComponent(new Label((total/target*100).toString()));
//Because you use a value inside a function, addItem should be initialized as final
addItem.addComponent(ctrResult);
But i can't do nothing for your code error because i can't see the full code here
I am notdoing a school project, so please do not be alarmed. I am doing some private programming to brush up. My program, a program of type .java, creates a form that asks for the boundaries and quantities of a lottery-drawing activity and acts on the generating based on the input.
Here's my problem. On the WIndows 2000 computer where I coded the program, shows itself, perfectly. That's only half the story. When I tried to put it on another computer, the program shows a blank window; it compiles and runs, but it shows a blank window. Now, I do consider version numbers to be factors, so I will provide the versions and ask for confirmation if those are the root of the evil.
On my original computer, which is Windows 2000, the version is 1.6.0_31-b05. The other computer, which is Windows 7 dual-booted with Linux Mint 17.2, is running 1.8.0_60-b27 and 1.8.0_00 respectively.
My program is not finished yet, but I'll worry about that later. What I'm hoping to do now is to get the program, such as it is, to run on the platforms of all my computers. Since Java is known for its portability, I expect it to run on all my computers. Is that a misconception?
Anyways, here's the code:
//Import class libraries
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
public class Lotterygui //Begin class
{
//VARIABLES FOR DATA COLLECTION
private JTextField lowerRange; //Lowest number
private JTextField higherRange; //Highest number
private JTextField quantity; //How many numbers to generate
private JTextArea displayArea; //What to display when the program is in use
//ADD WARNING CONSTANT FOR INVALID INPUT
private final String WARNING = "Please fill out valid data "
+ "and not leave anything out. "
+ "Also,do not enter any "
+ "zeroes.";
public Lotterygui()
{
//GUI CONFIGURATION
//Frame settings
JFrame jfrFrame = new JFrame("Lottery Program");
jfrFrame.setSize(300,400);
jfrFrame.setLocationRelativeTo (null);
jfrFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrFrame.setVisible(true);
jfrFrame.setResizable(false);
//Panel to hold the user input controls in place
JPanel jplInputs = new JPanel();
jplInputs.setLayout(new GridLayout(4, 2));
//CREATE INPUT CONTROLS
//Lowest range
JLabel jlblLowerRange = new JLabel("Lowest");
lowerRange = new JTextField();
//Highest range
JLabel jlblHigherRange = new JLabel("Highest");
higherRange = new JTextField();
//Quantity
JLabel jlblQuantity = new JLabel("Quantity");
quantity = new JTextField();
//Buttons and their respective action associations
//Generate numbers button
JButton jbtnGenerate = new JButton("Generate");
ActionListener alGenerate = new listenGenerate();
jbtnGenerate.addActionListener(alGenerate);
//Reset all values button
JButton jbtnReset = new JButton("Reset");
ActionListener alReset = new listenReset();
jbtnReset.addActionListener(alReset);
//ADD CONTROLS TO FORM
jplInputs.add(jlblLowerRange);
jplInputs.add(lowerRange);
jplInputs.add(jlblHigherRange);
jplInputs.add(higherRange);
jplInputs.add(jlblQuantity);
jplInputs.add(quantity);
jplInputs.add(jbtnGenerate);
jplInputs.add(jbtnReset);
//CREATE DISPLAY AREA AND ADD
//The display area used for showing generated numbers
displayArea = new JTextArea();
displayArea.setLineWrap(true);
displayArea.setText(WARNING);
//The control that sets autoscrolling for the display area
JScrollPane jspDisplayArea = new JScrollPane(displayArea);
jfrFrame.add(jspDisplayArea);
//Add the JPanels to the window
jfrFrame.add(jplInputs, BorderLayout.NORTH);
jfrFrame.add(jspDisplayArea);
}//END lotteryGUI constructor
//MAIN Method
public static void main (String[] args)
{
//CALL UP lotteryGUI CLASS
new Lotterygui();
}//END Main method
//GENERATE BUTTONS ACTION
private class listenGenerate implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//DECLARE VARIABLES
int low; //Lowest number
int high; //Highest number
int qty; //How many numbers
try //Monitor the input of above variables in the form
{
low = Integer.parseInt(lowerRange.getText());
high = Integer.parseInt(higherRange.getText());
qty = Integer.parseInt(quantity.getText());
}
catch (NumberFormatException nfe)
{
//RESET ALL FORM VALUES
reset();
//RESET VARIABLE VALUES
low = 0;
high = 0;
qty = 0;
}//END format errors try-catch
//CHECK IF PROGRAM CAN CONTINUE
if (low != 0 || high != 0 || qty != 0) //If valid
{
//Action pending
displayArea.setText("Generate here - incomplete");
}
else //If there are more one or more errors in the input
{
//ISSUE WARNING
JOptionPane.showMessageDialog(null, WARNING);
}//END IF continue CHECK
}//END actionPerformed method
}//END listenGenerate class
I've been looking up and down at the code. Can this that I did not reference any of the layouts outlined in import? I know it's not JPanel as I did try that can still the problem existed. Anything that will help me will be appreciated. Thank you.
You're calling
jfrFrame.setVisible(true);
first and then adding a bunch of components to the JFrame, and that's backwards and can result in a GUI that does not render components until it is resized or minimized and restored. In fact try this -- run your program, then minimize the blank GUI and restore it, and I'll bet you'll see your components.
I suggest that you swap this order around -- call jfrFrame.setVisible(true); last after adding everything to the GUI.
Thanks in advance for any help. So I've used input from JOptionPane many times before but this is confusing me. I only want to use the input from the paymentField which takes in ($0.00) a value from the user. Do I use an action listener for this and if so how or is there another way?
At the minute Im using showInputDialog but it brings up an extra unwanted text field. Also tried showConfirmDialog but couldnt seem to use what was entered.
//method used to display dialog box required add funds to wallet
public void getWalletBox() {
String[] cTypes = {"Maestro", "Visa Debit", "Mastercard", "American Express"};
JComboBox cardType = new JComboBox(cTypes);
cardType.setFont(new Font("Serifs", Font.BOLD, 16));
JTextField cardNumField = new JTextField(20); //width of text fields = 25
cardNumField.setFont(new Font("Serifs", Font.BOLD, 16));
//formats payment field using dollar prefix
NumberFormat paymentFormat = NumberFormat.getCurrencyInstance(Locale.US);
paymentField = new JFormattedTextField(paymentFormat);
paymentField.setValue(new Double(0.00));
paymentField.setFont(new Font("Serifs", Font.BOLD, 25));
paymentField.setEditable(true);
paymentField.setForeground(Color.green);
//array of objects used to add labels and fields to joptionpane
Object[] fields = {
"Card Type: ", cardType,
"Card Number: ", cardNumField,
"Add: ", paymentField
};
JOptionPane.showInputDialog(null, fields, "Wallet", JOptionPane.OK_CANCEL_OPTION);
}`
You have to define your own JDialog for that as that is much simple as compared to cutomize it using this method.
I'm trying to work to display a number of jtextfield according to one of the given values in a combobox.
So, I will have a drop down menu with let's say 1 to 4. If the user selects number 3, 3 textfields will be displayed. I've created the jcombobox with a selection of numbers. But I'm not sure how to implement this. If I'm not mistaken I need to use
ItemEvent.SELECTED
I think I need to create a reference to the JTextField object that will be available to the JComboBox's itemListener object.
Any help would be greatly appreciated.
I've added this to my class :
// aOption is the combobox I declared
aOptionComboBox.setModel(new DefaultComboBoxModel(new String[]{"1","2","3"}));
public void itemStateChanged(ItemEvent event) {
String num = (String)aOptionComboBox.getSelectedItem();
int num1 = Integer.parseInt(num);
JTextField[] textfields = new JTextField[num1];
for (int i = 0; i < num1; i++)
{
textfields[i] = new JTextField("Field");
getContentPane().add(textfields[i]);
textfields[i].setBounds(200, 90, 100, 25);
}
}
am I on a right track?
use the getSelectedItem() on the combobox. This will either yield a string or an integer (depending on how you implemented it). Next use a for-loop to determine the amount of JTextField's and store them in an array.
int amount = myJComboBox.getSelectedItem();
JTextField[] textfields = new JTextField[amount];
for (int i = 0; i < amount; i++) {
textfields[i] = new JTextField("awesome");
this.add(textfields[i]);
}
this way you can easily store the textfields and add them to your panel.
Some added information.
The textfield-array must be accesible outside the eventListener, so you must implement it in your class. that way the whole class can use it.