Java Swing dynamic JComboBox - java

I have populated a combobox B1 from database. When itemStateChanged event raises it should populate another combobox B2, but its not working.
ArrayList1 = //call method in database connection class()
for (int j = 0; j < ArrayList1.size(); j++)
{
if (j == 0)
{
combobox1.addItem("Select Any");
}
combobox1.addItem(ArrayList1.get(j));
}
combobox1.addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent ie)
{
String catName = (String)combobox1.getSelectedItem();
if (!catName.equalsIgnoreCase("Select Any"))
{
ArrayList2=//call method in DB class with cat_name as argument
for(int i=0;i < ArrayList2.size();i++)
{
if (i == 0)
{
combobox2.addItem("Select Any");
}
combobox2.addItem(ArrayList2.get(i));
}
}
}
});
first combobox gets populated from database, but after selecting any item from it second combobox keeps empty.
and why debugging this my computer hangs on?

you have to implements ComboBoxModel and add/remove/change Items in the Model, not in the JComboBox, nor somewhere in the Array, List or Vector, sure is possible but you have to execute your code on EDT and always replace Array, List or Vector for concreted JComboBox, don't do it that this way :-)
maybe you have problem with Concurency in the Swing, maybe changes are done, but outside EDT, more about your issues pass events wrapped into invokeLater() and multiple-jcombobox

DefaultComboBoxModel model = new DefaultComboBoxModel(yourstringarray);
item_combobox.setModel( model );
n ma problem get solved....

You must read:
http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
It will help you to deal with java comboboxes.
Seems you should use an ActionListener as event to populate second combobox.
For your debug problems you should check bug 6714678 from java bugtracker
-Dsun.awt.disablegrab=true
should solve your debug problem (since 2008)
See could not work for old jdks as on 2007 related bug 6517045 says:
after discussion we came to conclusion that this (debug on combobox events) is just one more place when it is not
wise to stop in debugger (the same is true for DnD, fullscreen).

Related

JavaFX Assigning action to all buttons in an array of arrays using for-loop

We have this warm up exercise where we're supposed to create this reallllly simple game which's UI is pretty much set up
.
I got the error "Local variable i defined in an enclosing scope must be final or effectively final".
I didn't understand it, so I googled it, but most of the problems are different.
While typing this question I found this in the stackoverflow suggestions:
Assigning an action to each button, in an array of buttons in JavaFX
But I simply don't understand. I'm learning programming/java from scratch. I hope JavaFX/GuI stuff isn't a hindrance?
The code below only includes my attempt to assign the actions. I separated it from the creation of the buttons for the time being to figure out what the problem is. The problem is only in the if and else conditions.
for(int i=0; i<=4; i++) {
for(int j=0; j<=4; j++) {
buttonGrid[i][j].setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
if (buttonGrid[i][j].getText() == "X") {
buttonGrid[i][j].setText("O");
} else {
buttonGrid[i][j].setText("X");
}
}
});
}
}
For now I just want the button's labels to change from X to O and from O to X as you click them. Btw. If I learn JavaFX and GUI, does it mean I HAVE to learn css? (Not that I don't want to, just.. not now)
If there is a need for the rest of the code to figure the problem:
http://textuploader.com/5b1kh
I'd also appreciate if someone could tell me how to do the Scenes in a more efficent way. (Btw, can I somehow lock the aspect ratio of the sides of all cells of a gridpane?)
I think that the answer in this question explains your problem very well and how to solve it Problems with local variable scope. How to solve it? You can not use i and j inside the Action handler.
Try this. [Notice that I've also changed the string comparison*]
for(int i=0; i<=4; i++) {
for(int j=0; j<=4; j++) {
final Button myButton = buttonGrid[i][j];
myButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
if ("X".equals(myButton.getText())) {
myButton.setText("O");
} else {
myButton.setText("X");
}
}
});
}
}
[*] How do I compare strings in Java?

Java JTable dynamic population

This is the first time I've ever tried using a Java Swing JTable, so I'm probably doing something silly.
I'm trying to dynamically update a JTable within a JFrame on a GUI, this is the code I've currently written:
private void updateGUI(String input, DefaultTableModel model, int elements) { //3 elements
try {
Object[] cellData = input.split("!\\*");
Iterator it = Arrays.asList(cellData).iterator();
int rowCount = cellData.length / numberOfElements;
model.setRowCount(rowCount);
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < numberOfElements; j++) {
model.setValueAt(it.next(), i, j);
}
}
} catch (Exception uhoh) {
System.out.println("Couldn't add new string to gui");
uhoh.printStackTrace();
}
}
Essentially, I pass the updateGUI function a String containing elements, separated by !*. At the moment the data looks like this:
firstName!*123456!*lastName
This then gets split up into the Object[], and I'm currently using an iterator to put it into the table cells.
However, I keep getting ArrayIndexOutOfBoundsException: 27 >=27 being thrown, so it looks I'm doing something wrong with the cell generation/population.
I'm sure there is a much better way of doing this, but after reading through a few examples, I'm still a bit puzzled.
Any suggestions or advice would be greatly appreciated.
Thanks!
The easiest way I found to do this is to write a custom TableModel. I've written many of them and they not that difficult when you get your head around them. Given the code you posted you've have this message.
Derive your TableModel class from AbstractTableModel. This will handle the registration of any model listeners (one of which will be your JTable). Then on insert you need to call fireXXX() to notify all the listeners that there is new data. From your example code where you are replacing all the data this would be fireTableDataChanged().
Have a look at the Glazedlists project: http://www.glazedlists.com/
It solves this and a lot more in a very easy to use way. Documentation on your specific case can be found at http://www.glazedlists.com/propaganda/features#TOC-Easy-TableModels

Efficeint way to manipulate multiple Checkbox items

I have a 6 JCheckBoxes in the UI and based one some user operations, I have to change the state of the JCheckBoxes, like enabling,selecting and making it invisible. So, instead of having the code as separate for each JCheckBox, I have used the following code,
Object[] checkBoxCollection = null;
checkBoxCollection = new Object[]{qualityChkBox1, qualityChkBox2, qualityChkBox3, qualityChkBox4, qualityChkBox5, qualityChkBox6};
for (int i = 0; i < checkBoxCollection.length; i++) {
JCheckBox checkBox = (JCheckBox) checkBoxCollection[i];
if (checkBox.getText().equals("Name") || checkBox.getText().equals("RollNo")) {
checkBox.setSelected(true);
} else {
checkBox.setSelected(false);
}
}
Similarly, I have some places in code, where I am keep on changing the state like setSelected(false) and setSelected(true).
Is there any way that I can do more better than this ?
Thanks in advance.
As shown here, you may be able to use EnumSet to define sets that represent coherent states of your model. Then your check boxes can share a common Action that conditions each JCheckBox according to that defined state.

Issue changing value in ArrayList from GUI

I have an ArrayList called conditionList which stores condition names.
Whenever one is added/edited or deleted, the Lists on my GUI update no problems.
You can see below that i use 2 models... a DefaultListModel called condListModel and a DefaultComboBoxModel called conditionModel.
The code i have below is for the method editCondition(), at this stage the text is already changed on the GUI and is being submitted here. On my GUI, after ive submitted the change, the ComboBox and JList change no problem so im sure that the model changes are correct.
HOWEVER MY PROBLEM IS: When i save the ArrayList conditionList through serialization, and then load it back up, the change is gone. SO I think there is problem in my code with changing the String Value in the ArrayList(named conditionList), can anyone have a look and see if u notice an issue
String conString = jListCondition.getSelectedValue().toString();
for(String c: conditionList)
{
if(conString.compareTo(c) == 0)
{
String temp = entConName.getText();
c = temp;
//edit the Condition jList model
int x = condListModel.indexOf(conString);
condListModel.setElementAt(temp, x);
jListCondition.setModel(condListModel);
//edit the Condition comboBox model
int i = conditionModel.getIndexOf(conString);
conditionModel.insertElementAt(temp, i);
conditionModel.removeElement(conString);
entCondition.setModel(conditionModel);
//reset buttons
editConConfirm.setEnabled(false);
editCon.setEnabled(false);
deleteCon.setEnabled(false);
entConName.setText("");
addCon.setEnabled(true);
}
}

GWT - ListBox - pre-selecting an item

I got a doubt regarding pre-selecting(setSelectedIndex(index)) an item in a ListBox, Im using Spring + GWT.
I got a dialog that contains a panel, this panel has a FlexPanel, in which I've put a couple ListBox, this are filled up with data from my database.
But this Panel is for updates of an entity in my database, thus I wanted it to pre-select the current properties for this items, allowing the user to change at will.
I do the filling up in the update method of the widget.
I tried setting the selectedItem in the update method, but it gives me an null error.
I've searched a few places and it seems that the ListBox are only filled at the exact moment of the display. Thus pre-selecting would be impossible.
I thought about some event, that is fired when the page is displayed.
onLoad() doesnt work..
Anyone have something to help me out in here?
I really think you can set the selection before it's attached and displayed, but you have to have added the data before you can select an index. If this is a single select box you could write something like this:
void updateListContent(MyDataObject selected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
theListBox.setSelectedIndex(list.indexOf(selected));
}
If this is a multiple select box something like this may work:
void updateListContent(List<MyDataObject> allSelected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theMultipleListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
for (MyDataObject selected : allSelected) {
theMultipleListBox.setItemSelected(list.indexOf(selected), true);
}
}
(Note I haven't actually compiled this, so there might be typos. And this assumes that the selected element(s) is really present in the list of possible values, so if you cant be sure of this you'll need to add some bounds checking.)
I've been happily setting both the values and the selection index prior to attachment so as far as I'm aware it should work. There's a bug however when setting the selected index to -1 on IE, see http://code.google.com/p/google-web-toolkit/issues/detail?id=2689.
private void setSelectedValue(ListBox lBox, String str) {
String text = str;
int indexToFind = -1;
for (int i = 0; i < lBox.getItemCount(); i++) {
if (lBox.getValue(i).equals(text)) {
indexToFind = i;
break;
}
}
lBox.setSelectedIndex(indexToFind);
}
Pre-selection should work also with setValue()-function. Thus, no complicated code is needed.

Categories

Resources