Efficeint way to manipulate multiple Checkbox items - java

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.

Related

How do I retrieve the component type used at a specific cell in a JTable?

I've created a JTable whose columns contain a variety of different components. The last five columns either contain nothing (a DefaultTableCellRenderer with no value) or a JRadioButton using a custom renderer and editor. The renderer creates and returns a new radioButton in the cells I need one, and I want to access these radio buttons from my panel class to add them to a ButtonGroup. I am using the following piece of code that I wrote:
protected void setButtonGroups() {
buttonGroups = new ArrayList<ButtonGroup>();
for (int i = 0; i < tableModel.getRowCount(); i++) {
ButtonGroup currentGroup = new ButtonGroup();
for (int j = 0; j < tableModel.getColumnCount(); j++) {
if (table.getComponentAt(i, j) != null) {
currentGroup.add((JRadioButton)table.getComponentAt(i, j));
}
}
}
buttonGroups.add(currentGroup);
}
}
getComponentAt() keeps returning null regardless of what is contained in the cell, whether it be a JCheckBox, JRadioButton, JComboBox... everything is returned as null.
Is there an alternative way to get the cell's component? Or is there a way for me to get this to work? Thank you!
If you have a tableModel from table.getModel(). Then you can call model.getValueAt(row,col)
I am not sure why you are putting Swing Components inside a JTable. Are you using it for formatting? If so look into LayoutManagers. If you want to edit values in a table, you might want to look into extending TableCellEditor. If you really want to put components in your table. Consider extending the DefaultTableCellRenderer to return your component. You will want to override getTableCellRendererComponent().

Remove column from column control popup menu

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)

Java Swing dynamic JComboBox

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).

How to get a handle to all JCheckBox objects in order to loop?

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.

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