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.
Related
Is it possible to control whether a column should be available in a column control popup menu? I'm aware of toggling (Disable/enable using CheckBoxList) and gray-out the column. But I do not want column entry in popup menu as The column is must-have column in Jtable. I'm using the JXTable. Anyone that have any hints?
A TableColumnExt has a property hideable which effectly disables the hiding. It is still shown in the popup and you can toggle the checkbox (that's a bug, just filed - the menu item should be disabled ;), but at least the column isn't hidden. To work around the bug, you can implement a custom column control (as Robin correctly suggested) which doesn't add the checkbox, something like:
JXTable table = new JXTable(new AncientSwingTeam());
// here the hideable property is configured manually,
// in production code you'll probably have a custom ColumnFactory
// doing it based on some data state
table.getColumnExt(0).setHideable(false);
ColumnControlButton columnControl = new ColumnControlButton(table) {
#Override
protected ColumnVisibilityAction createColumnVisibilityAction(
TableColumn column) {
if (column instanceof TableColumnExt
&& !((TableColumnExt) column).isHideable())
return null;
return super.createColumnVisibilityAction(column);
}
};
table.setColumnControl(columnControl);
table.setColumnControlVisible(true);
As to not including the menu item: when introducing the hideable property, we decided to go for keeping the item in the list but disable it because users might get confused not seeing all columns in the control. So once the bug will be fixed (just done, committed as of revision #4315), I would recommend to remove the custom column control again. Just my 2 euro-cents, though :-)
ColumnControlButton#createColumnVisibilityAction looks like the method you are looking for. According to the documentation:
Creates and returns a ColumnVisibilityAction for the given TableColumn. The return value might be null, f.i. if the column should not be allowed to be toggled
you can return null for your case.
You should be able to plug this in by using the JXTable#setColumnControl method.
First way:
myTable().getColumnExt(_column_number_).setHideable(false);
This works smooth but has one UI drawback: text in menu is gray and thick is black - bad user experience.
So try to fix it, text will be gray and thick won't be here:
public class MyTable extends JXTable
{
public MyTable(AbstractTableModel model)
{
//first two columns won't be hiddeable
ColumnControlButton controlButton = new ColumnControlButton(this)
{
#Override
protected ColumnControlPopup createColumnControlPopup()
{
return (new NFColumnControlPopup());
}
class NFColumnControlPopup extends DefaultColumnControlPopup
{
#Override
public void addVisibilityActionItems(List<? extends AbstractActionExt> actions)
{
for(int i = 0; i < actions.size(); i++)
{
AbstractActionExt action = actions.get(i);
JCheckBoxMenuItem chk = new JCheckBoxMenuItem(action);
//Disabling unwanted items but they will be still shown for smooth user experience
if(i == 0 || i == 1)
{
chk.setEnabled(false);
chk.setSelected(false);
//chk.setIcon(new ImageIcon(Icons.class.getResource("check.png")));
}
else
{
chk.setSelected(true);
}
chk.addItemListener(action);
super.addItem(chk);
}
}
}
};
this.setColumnControl(controlButton);
}
}
and if you need to hide controls for "show horizontal scrollbar", "pack" and "pack all" add into code:
//remove items for horizontal scrollbar, pack and packall
this.getActionMap().remove("column.horizontalScroll");
this.getActionMap().remove("column.packAll");
this.getActionMap().remove("column.packSelected");
right after calling super(model)
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.
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);
}
}
I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like
if(checkBox1.isSelected()) {
myString.append(checkBox.getText());
}
That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this:
public class CheckBoxPanel extends JPanel {
private static final long serialVersionUID = 1L;
public CheckBoxPanel(String title, String... options) {
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// make one checkbox for each option
for (String option : options) {
JCheckBox b = new JCheckBox(option);
b.setActionCommand(option);
add(b);
}
}
}
This is called like this:
toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper",
"Black Olives", "Mushrooms", "Extra Cheese",
"Pepperoni", "Sausage");
So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names.
Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.
I'm assuming you're not allowed to alter the CheckBoxPanel code at all. Which seems like a useless exercise, because in the real world, you'd think that if CheckBoxPanel where a class being provided to you (e.g. in a library) it would include a way of getting the selected options. Anyway, due to the limitation, you could do something like this:
for( int i=0; i<checkBoxPanel.getComponentCount(); i++ ) {
JCheckBox checkBox = (JCheckBox)checkBoxPanel.getComponent( i );
if( checkBox.isSelected() ) {
String option = checkBox.getText();
// append text, etc
}
}
I suggest you maintain a list of checkboxes:
List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
and before add(b) do:
checkboxes.add(b);
You may then iterate through the list of checkboxes in the buttons action-code using a "for-each" loop construct:
for (JCheckBox cb : checkboxes)
if (cb.isSelected())
process(cb.getText()); // or whatever.
Alternatively, if you need to keep track of the specific index:
for (int i = 0; i < checkboxes.size(); i++)
if (checkboxes.get(i).isSelected())
....
I would suggest that you dont put each of the checkboxes in a List when you create them. Instead, in your shared ActionListener, you maintain a Set of all selected checkboxes. Use the getSource method on the ActionEvent to identify which checkbox the user selected and then cast it to a JCheckBox. If isSelected() returns true for the item in question, attempt to add it to your selectedItems Set. If it is not, then attempt to remove it.
You can then just iterate over the subset of all items (only those that are selected) and print them to the console.
I have generated a GUI from netbeans in which I have placed a combobox too.
By default, the items in combobox are item1, item2, item3, item4.
But I want my own items. Netbeans doesn't allow editing generated code so how can i edit the comnbobox according to me.
Note: I know one method by editing the "model" property of that jComboBox but I don't want to do it like that because I want various items (which are in an array) in that jComboBox so I want to pass that array in that jComboBox like as follows:
jComboBox2 = new javax.swing.JComboBox();
String [] date = new String[31];
for(int i = 0; i < 31; i++) {
date[i] = i + 1;
}
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
There are 2 approaches I am aware of:
Simple approach - After the call to initComponents() in the constructor add you code to build your model and call jComboBox2.setModel(myModel) to set it. So the constructor would look something like:
public SomeClass() {
initComponents();
String [] date = new String[31];
for(int i = 0; i < 31; i++) {
date[i] = i + 1;
}
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(date));
}
Complex approach - add a readable property that holds the desired model. For example:
private ComboBoxModel getComboBoxModel()
{
String[] items = {"Item A", "Item B", "Item C"};
return new DefaultComboBoxModel(items);
}
Then, in the jComboBox2 property sheet, click the button to edit the model.
In the editor panel change the dropdown from Combo Box Model Editor to Value from existing component.
Select Property. Choose the comboBoxModel property. Click OK
I tried the second way once. Never really used it again. Too much work, no real much gain. Plus it displays an empty combo box in the designer which just makes layout harder.
I use the first approach, plus use NetBean's model editor to supply some representative values for the model. That gives me the sensible size behavior in the designer at the cost of one unnecessary line in initComments().
Using Netbeans NEON and other netbeans version
1. Go to the properties of the combobox
2. Then go to model
you can inject your code by using "custom code" feature in the GUI editor for the "model" of combobox
public NewJFrame() {
initComponents();
reformatComboBox();
}
private void reformatComboBox() {
JComboBoxName.removeAllItems();
JComboBoxName.addItem("item1");
JComboBoxName.addItem("item2");
}
Completing blurec answer (I cannot comment yet), in the GUI editor select the comboxbox, go properties, then model, then hit the three dots. Then select Custome Code and add your code, for instance:
new DefaultComboBoxModel<>(functionThatReturnsAnStringArray())
For the posterity:
Right click the ComboBox and select Customize Code. Here at the comboBox.setModel, in the left select custom property.
After new String, add your values in the following form:
Value 1: Integer.toString(myInt1)
Value 2: Integer.toString(myInt2)
If your variables are int of course. If not just put the String variable and you are done.
Hope it helps.