I have two combo boxes. The first contains some operator (+ , - ,* ,/) and the second one contains some value from 0 to 10. When user select (/) in first combo box I want the second one to show a value from 2 to 10 instead of 0 to 10.
I've tried this:
String[] operators = {"+","-" ,"*", "/"};
String[] number = {"0","1","3"....."10"};
divisionModel= new DefaultComboBoxModel(new String[]{"2","3","4","5".."10"});
operatorCombo = new JComboBox(operators);
numberCombo = new JComboBox(number);
operatorCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (operatorCombo .getSelectedItem().equals("/")){
numberCombo .setModel(divisionModel);
}
my problem is when I select ("/") the numberCombo works fine and show me numbers from 2 to 10 but when I click on another operator it still show me the numbers from 2 to 10 instead 0 to 10.How can I solve this problem?!
Thanks
// always compare objects using equals()
if (operatorCombo.getSelectedItem().equals("/")) {..
As to updating the 2nd combo, create a new model for it and call setModel(ComboBoxModel).
You might look at this example that shows how the selection made in one JComboBox can change the appearance of related JComboBox by using a different DefaultComboBoxModel.
Related
I'm using a JMenu (named Count) with four JMenuItems (named Inc, Dec, Reset, Quit). When I click on any of the menuitems I want it to display the integer in the JTextArea. For example, everytime I click on Inc it should show the integers vertically listed starting from 0. The issue right now is that when I press the Dec menuitem its not taking the last number listed.
I tried to use the getText method but I keep getting a NumberFormatException and saying that the input string is a bunch of numbers e.g.:
0
1
2
3
4
From what I can tell, I am aware that I need to be able to keep track of the last number in a way that all menuitems (aside from the quit menuitem) can access it and change it. I just have no idea how to do it.
Here is one of the ways that I've tried where it gives me the error I mentioned above.
//newLine = "\n";
public void actionPerformed(ActionEvent ae) {
String ac = ae.getActionCommand();
if(ac.equals("Inc")) {
jta.append(count + newLine);
count++;
}
else if(ac.equals("Dec")) {
count = Integer.parseInt(jta.getText());
countText = Integer.toString(count);
jta.append(countText + newLine);
count--;
}
else if(ac.equals("Reset")) {
jta.selectAll();
jta.replaceSelection("0");
count = 0;
}
else if(ac.equals("Quit")) {
System.exit(0);
}
}
I was expecting
0
1
2
3
4
3
2
1
to be displayed in the TextArea when I click on Inc and Dec
But instead its just
0
1
2
3
4
and then I get a NumberFormatException saying that the input string is:
0
1
2
3
4
If possible, I would like the input string to be just the last integer in the textarea.
I hope this makes sense. This is my first time making a post on stackoverflow.
When you get the text, it has returned "0 1 2 3 4" which cannot be parsed an integer, therefore the exception.
If you want to get the last integer in the text field, you need to retrieve the text and find the substring that represents the last integer. Look at the javadocs for String, especially the lastIndexOf(), split(), and substring() methods.
If you have placed each integer on a separate line, and have kept track of the last number entered in an instance variable "count", then you just need to call jta.append( (count-1) + newLine); without having to retrieve the text at all.
Note that your code does not save the last number entered - it saves (last+1)
my data comes from query like this to my radio buttons:
radio1.setText(Question.get(i).getChoiceOne()) // assign ist choice to ist radio button
radio2.setText(Question.get(i).getChoiceTwo()) // assign second choice to second radio
radio3.setText(Question.get(i).getcorrectchoice()) // assign correct choice to third radio button
In this case each time the correct answer is assigned to third radio button which makes the quiz predictable.. Can I do it in some way where the correct choice some times assign to first radio, some times to second and so on?
You could do following:
String one = Question.get(i).getChoiceOne();
String two = Question.get(i).getChoiceTwo();
String three = Question.get(i).getcorrectchoice();
// construct list from questions.
List<String> choices = Arrays.asList(one, two, three);
// give random order to list
Collections.shuffle(choices);
// set radio button texts
radio1.setText(choices.get(0));
radio2.setText(choices.get(1));
radio3.setText(choices.get(2));
int i = (Math.random() * 1000)%3;// generate a values between 0-2
String[] answers = new String[3];
answers[i] = Question.get(i).getcorrectchoice();// i is the index of right answer
// insert the 2 other answers, what ever i you chose (i+1)%3 will put them in the remaining 2 places
answer[(i+1)%3] = Question.get(i).getfirstchoice();
answer[(i+1)%3] = Question.get(i).getsecondchoice();
i = (i+1)%3;// the original value of i
// insert radios
radio1.setText(answers[0]);
radio2.setText(answers[1]);
radio3.setText(answers[2]);
// get the right answer; get the text of the selected radio
if(textOfselectedRadio.quals(answers[i])){
// correct
}
For a Java Schoolproject I would like to have a table from witch you can select a Item that then shows up on a new window. In that window you can change things like ComboBoxes and others. My only problem is, that I dont know how to select the Item of the ComboBox I need. All the ComboBoxItems are Objects and I dont know how to handle this.
My ComboBoxItem looks like this:
Apprentice [person=Person, DB ID: 9, Kappa Kappa, Kappastrasse 21,
CityID: 4521, kappa.kappa#kappa.ch, idpersonen=9,
vertragsstart=2020-01-02, ausbildungsct=2, id=6]
Now, my Question is, how do I select the ComboBoxitem where the id=6, all the things I found needed the whole Object to select a special Item. How would you guys go at this problem?
Good luck and thanks for the Help.
Bono
All I had to do was a really simple while with a for and a if.
int trys = 0;
while (0 == apprenticeComboBoxZeugnis.getItemCount() && trys < 10000) {
System.out.println(apprenticeComboBoxZeugnis.getItemCount());
for (int i = 0; i < apprenticeComboBoxZeugnis.getItemCount(); i++) {
apprenticeComboBoxZeugnis.setSelectedIndex(i - 1);
int spacko = getApprenticeCombo();
if (spacko == lehrlingsid) {
TableFilterListenerZeugnis tableFilterListenerZeugnis = new TableFilterListenerZeugnis(
this);
tableFilterListenerZeugnis.updateNoten();
break;
}
}
trys++;
}
This first trys until the number of Objects is not = 0 and after that looks at every object, cuts out the id with getApprenticeCombo() and compares it with my id I allready have. If they match it breaks out and is done with it.
Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.
I have a simple interface that is designed to select one or more seats in a theater and reserve them for yourself.
I have three columns: zone / row / seat. You select the first to populate the second, and the second to populate the third.
When I select them the first time no problem.
If I change the second row, the third row re-populates (in this case all rows have the same number of seats) it does not break!
However if I change the first row everything breaks!
Now the reason for this is kinda clear, but I don't understand exactly why this is.
This is the first list event trigger:
List_Zona.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if (! arg0.getValueIsAdjusting()){
RowListModel.clear(); // second list
SeatListModel.clear(); // third list
List_Rand.clearSelection(); // second list
List_Scaun.clearSelection(); // third list
int[] rows = self.repository.getRowsForZone(
List_Zona.getSelectedValue().toString()
);
int index = 0;
while (rows[index]!=0) {
RowListModel.addElement(String.valueOf(rows[index]));
index++;
}
}
}
});
It should clear the other column selections so it should not interfere with this next trigger (second column), but apparently it does, or something happens which I don't get:
List_Rand.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
if (! arg0.getValueIsAdjusting()){
SeatListModel.clear();
int[] seats = self.repository.getSeatByZoneAndRow(
List_Zona.getSelectedValue().toString(),
Integer.parseInt(List_Rand.getSelectedValue().toString())//HERE
);
int index = 0;
while (seats[index]!=0) {
SeatListModel.addElement(String.valueOf(seats[index]));
index++;
}
}
}
});
It can't parse the integer because the second column should be cleared, but it's not ? But even though it's not ... it is ?
What I'm trying to say: The second column should be clear (it's not) but if it's not then the error should not occur, but it does.
I hope this makes some sense!
Can anyone spot the problem ? Should I provide more code ?
The error is a NullPointerException at the second column, because something fishy is happening there (again: at the integer parsing).
By my mind the second column's valueChanged should not trigger at all when I click an item in the first column. It should just clear the other two and that's that. Why am I wrong ?
P.S. First Code snippet is responsible for the second one breaking the program.
Maybe I should also rephrase the question How can I safely clear everything when I re-select a new "Zone" (Zona) - Column one ?
The first listener clears the selection of List_Rand. That makes the selection change: it goes from "the index i is selected" to "no index is selected", so the second listener is invoked. And in the second listener, you're trying to call a method on the selected value of List_Rand. Since you just cleared the selection, there's no selected value anymore, hence the NullPointerException.
Side note: your code is very hard to read, because it doesn't respect the Java naming conventions. Variables start with a lowercase letter, and are camelCased (no underscore in their name).
Other side note : what's the point in calling parseInt(selectedValue.toString())? If the list contains Integer instances, the cast the value to Integer directly. If it contains String, then why not store Integers instead, since this is what you want the list to contain?