I'm trying to make a currency converter program, and I want JComboBox items to get replaced from the other JComboBox when I hit the convert button.
I know the mistake is to try and convert String to integer, but I see no other way to set JComboBox's contents.
A screenshot from NetBeans with my results in case the code is hard to understand.
Below is the code of jButton:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
for(int a = 0; a < 4; a++){
String box2 = (currency2.getItemAt(a));
System.out.println("List items b4 conversion, JComboBox1: "+ currency1.getItemAt(a));
System.out.println("List items b4 conversion, JComboBox2: "+ box2+"\n");
System.out.println("--End of first 2 items--");
System.out.println("JComboBox2 after conv" +currency1.getItemAt(Integer.parseInt(box2)));
}
}catch (NumberFormatException e){
System.out.println("error");
}
}
Here's what it prints:
List items b4 conversion, JComboBox1: EUR
List items b4 conversion, JComboBox2: ALL
--End of first 2 items--
error
Meanwhile, when I remove: System.out.println("JComboBox2 after conv" +currency1.getItemAt(Integer.parseInt(box2))),it prints all items of 2 JComboBoxes as expected.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String txt1 = (String) JComboBox1.getSelectedItem();
String txt2 = (String) JComboBox2.getSelectedItem();
jComboBox1.setSelectedItem(txt2);
jComboBox2.setSelectedItem(txt1);
}
Related
I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).
I am trying to perform action by selecting a value in Combobox and after selection, based of the value selected Jlist should be updated. But list is taking value only first time but its not getting updated while changing the values. However Values are coming and action is performed as I can see values are coming in consol.My code is as follows:
ArrayList< String> ModuleNames = GetModuleNames();
String[] ModuleNames1 = ModuleNames.toArray(new String[ModuleNames.size()]);
comboModuleName = new JComboBox(ModuleNames1);
comboModuleName.setEditable(true);
comboModuleName.setSelectedItem(null);
comboModuleName.setBounds(280,80,350,40);
panel.add(comboModuleName);
comboModuleName.addActionListener(new ActionListener() {
#SuppressWarnings("unchecked")
#Override
public void actionPerformed(ActionEvent e) {
String currentSelectedValue = comboModuleName.getSelectedItem().toString();
System.out.println("selected value is "+currentSelectedValue);
try
{ //collecting values from a function and want to populate in the list,currentSelectedValue
//currentSelectedValue is the value selected in the combobox based on this value function //returns some values as a arraylist
ArrayList CurrentModuleFunctions = getFunctionAndParametereNames(currentSelectedValue);
Vector reflectedValues = new Vector();
for (int i = 0; i < CurrentModuleFunctions.size(); i++) {
reflectedValues.addElement(CurrentModuleFunctions.get(i));
}
if(e.getSource() == comboModuleName) {
listFunctionNames = new JList(reflectedValues);
listFunctionNames.setBounds(280,140,350,140);
panel.add(listFunctionNames);
}
}
catch (ClassNotFoundException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
I am not sure why Jlist is not getting updated as I can get the values when I am selecting new value in combobox.
Instead of creating the JList inside actionPerformed() method,create it outside
listFunctionNames = new JList();
listFunctionNames.setBounds(280,140,350,140);
panel.add(listFunctionNames);
and inside actionPerformed(),just set the values
listFunctionNames.setListData(reflectedValues);
When the code below is run and the Beta check box is selected, then the Alpha check box, the text reads "Selected check boxes: Alpha, Beta" not "Selected check boxes: Beta, Alpha". Why do they appear in the opposite order to how they were selected?
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CBDemo implements ItemListener {
JLabel jlabSelected;
JLabel jlabChanged;
JCheckBox jcbAlpha;
JCheckBox jcbBeta;
JCheckBox jcbGamma;
CBDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("Demonstrate Check Boxes");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(280, 120);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create empty labels.
jlabSelected = new JLabel("");
jlabChanged = new JLabel("");
// Make check boxes.
jcbAlpha = new JCheckBox("Alpha");
jcbBeta = new JCheckBox("Beta");
jcbGamma = new JCheckBox("Gamma");
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha.addItemListener(this);
jcbBeta.addItemListener(this);
jcbGamma.addItemListener(this);
// Add checkboxes and labels to the content pane.
jfrm.add(jcbAlpha);
jfrm.add(jcbBeta);
jfrm.add(jcbGamma);
jfrm.add(jlabChanged);
jfrm.add(jlabSelected);
// Display the frame.
jfrm.setVisible(true);
}
// This is the handler for the check boxes.
public void itemStateChanged(ItemEvent ie) {
String str = "";
// Obtain a reference to the check box that
// caused the event.
JCheckBox cb = (JCheckBox) ie.getItem();
// Report what check box changed.
if(cb.isSelected())
jlabChanged.setText(cb.getText() + " was just selected.");
else
jlabChanged.setText(cb.getText() + " was just cleared.");
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
jlabSelected.setText("Selected check boxes: " + str);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CBDemo();
}
});
}
}
When any check box is clicked itemStateChanged() is called, the order of the string is driven by the order of your str+= statements in the code, not the temporal order of the clicks.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
To achieve the desired behaviour
store the selection events in some kind of ordered structure, e.g. a List that itemStateChanged updates and then displays.
Use different ItemListener instances for each checkbox, or use the ItemEvent parameter to determine where the event came from to update the structure accordingly
Try changing the 3 ifs to a single:
if (cb.isSelected()) {
selectionOrder.add(cb.getText()); // will return Alpha, Beta depending which is selected
}
jlabSelected.setText("Selected check boxes: " + selectionOrder);
Where selectionOrder is a field at the top of your CBDemo class
private List<String> selectionOrder = new ArrayList<String>();
This will obviously keep growing the list indefinitely, but fine for a demo.
Since Your order of Appending value to String is
Alpha --then-->Beta--then-->Gamma
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
}
if(jcbBeta.isSelected()) {
str += "Beta ";
}
if(jcbGamma.isSelected()) {
str += "Gamma";
}
So No Matter in which order you select the checkbox .
To achieve your desired output Use
// Report all selected boxes.
if(jcbAlpha.isSelected()) {
str += "Alpha ";
jcbAlpha.setSelected(false);// So when Next Time you click on other checkbox this condtion does not append result to Str
}
if(jcbBeta.isSelected()) {
str += "Beta ";
jcbBeta.setSelected(false);
}
if(jcbGamma.isSelected()) {
str += "Gamma";
jcbGamma.setSelected(false);
}
My application is constructed as follows:
Main window allows user to select CSV file to be parsed
JOptionPane appears after a CSV file is selected and the JOptionPane contains a drop-down menu with various choices; each of which generates a separate window
Currently, the JOptionPane closes after a selection is made from the menu and the "OK" button is clicked
I am looking for a way to force the JOptionPane to remain open so that the user can select something different if they want. I would like the JOptionPane to be closed only by clicking the "X" in the upper right corner. I am also open to other possibilities to achieve a similar result if using a JOptionPane isn't the best way to go on this.
Here is the relevant block of code I'm working on:
try
{
CSVReader reader = new CSVReader(new FileReader(filePath), ',');
// Reads the complete file into list of tokens.
List<String[]> rowsAsTokens = null;
try
{
rowsAsTokens = reader.readAll();
}
catch (IOException e1)
{
e1.printStackTrace();
}
String[] menuChoices = { "option 1", "option 2", "option 3" };
String graphSelection = (String) JOptionPane.showInputDialog(null,
"Choose from the following options...", "Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
menuChoices, // Array of menuChoices
menuChoices[0]); // Initial choice
String menuSelection = graphSelection;
// Condition if first item in drop-down is selected
if (menuSelection == menuChoices[0] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option1();
}
if (menuSelection == menuChoices[1] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option2();
}
if (menuSelection == menuChoices[2] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option3();
}
else if (graphSelection == null)
{
log.append("Cancelled." + newline);
}
}
I would like for the window with the choices to remain open even after
the user has selected an option so that they can select another option
if they wish. How do I get the JOptionPane to remain open instead of
its default behavior where it closes once a drop-down value is
selected?
this is basic property, by default JOptionPane is disposed, this isn't possible without dirty hacks, don't do that
use JDialog (could, may be undecorated) with proper value for ModalityType
you can to use some of variations for Java & Ribbon
you can to put desired choices to the JComboBox or JMenu with JMenuItems (very nice of ways) to the JLayer or GlassPane
I think that this is standard job for JMenu or JToolBar
In either of these option panes, I can change my choice as many times as I like before closing it. The 3rd option pane will show (default to) the value selected earlier in the 1st - the current value.
import java.awt.*;
import javax.swing.*;
class Options {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Object[] options = {
"Option 1",
"Option 2",
"Option 3",
"None of the above"
};
JComboBox optionControl = new JComboBox(options);
optionControl.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
System.out.println(optionControl.getSelectedItem());
String graphSelection = (String) JOptionPane.showInputDialog(
null,
"Choose from the following options...",
"Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
options, // Array of menuChoices
options[3]); // Initial choice
System.out.println(graphSelection);
// show the combo with current value!
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
I think Michael guessed right with a JList. Here is a comparison between list & combo.
Note that both JList & JComboBox can use a renderer as seen in the combo. The important difference is that a list is an embedded component that supports multiple selection.
The following solution won't give you a drop-down menu but it will allow you to select multiple values.
You can use a JList to store your choices and to use JOptionPane.showInputMessage like this:
JList listOfChoices = new JList(new String[] {"First", "Second", "Third"});
JOptionPane.showInputDialog(null, listOfChoices, "Select Multiple Values...", JOptionPane.QUESTION_MESSAGE);
Using the method getSelectedIndices() on listOfChoices after the JOptionPane.showInputDialog() will return an array of integers that contains the indexes that were selected from the JList and you can use a ListModel to get their values:
int[] ans = listOfChoices.getSelectedIndices();
ListModel listOfChoicesModel = listOfChoices.getModel();
for (int i : ans) {
System.out.println(listOfChoicesModel.getElementAt(i));
}
I'm trying to validate the input of multiple text boxes (i.e. they should be a number), and found the useful code snippet below here.
However, if I have three text boxes (text, moreText and evenMoreText), how can I apply a verify listener with the same functionality to each, without having to repeat the (.addVerifyListener(new VerifyListener() {...) code three times?
I don't want to implement a switch statement or similar (to decide which text box to apply it to), I want something more generic (that I can perhaps make available for other classes to use in the future).
text.addVerifyListener(new VerifyListener() {
#Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
Define the VerifyListener beforehand and get the actual Text from the VerifyEvent:
VerifyListener listener = new VerifyListener()
{
#Override
public void verifyText(VerifyEvent e)
{
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try
{
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
}
catch (final NumberFormatException numberFormatException)
{
// value is not decimal
e.doit = false;
}
}
};
// Add listener to both texts
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
If you want to use it in other places as well, create a new class:
public class MyVerifyListener implements VerifyListener
{
// The above code in here
}
and then use:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);