In my form I've created JSpinner and JComboBox elements. Depending on the changing of JComboBox I have to use the different Spinner models. So in ComboBox listener I write spinner = new JSpinner(newModel), but it change nothing on form.
How to recreate element to see the difference?
// Create default Spinner
count = new JSpinner();
// Trying to replace spinner
product.addActionListener(e -> {
JComboBox source = (JComboBox) e.getSource();
String selectedItem = (String) source.getSelectedItem();
...
SpinnerNumberModel numberModel = getNewNumberModel(...)
count = new JSpinner(numberModel);
count.setModel(numberModel);
// repaint(); revalidate() - also don't working
});
You should not reallocate the spinner every time. Just replace its model. You are allocating a new instance of JSpinner in you action listener and change its model. But this new instance is not part of your panel and not visible. Remove count = new JSpinner(numberModel); from the action listener. And change the model of the existing spinner.
Related
I am new to JComboBox
I have 4 JComboBoxes: specialite, etudiant, annee, and semestre.
I need to get the selected item from the 4 of them each time I change the selected item and add the result to the ScrollPane (groupe des matieres ouvertes)
Please look into the below JComboBox basic example given by Java. Use getSelectedItem() of JComboBox in actionPerformed() method of each combo box whenever an item got selected in it.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateScrollpane(petName); // Update your scrollpane
}
Do the same thing for all of your 4 dropdowns and update the scrollpane
I am working with vaadin 8.1.0 grid. I need to insert checkbox as a column and also as column header. when I click checkbox in column header, all column checkbox should be checked. That is working fine. But the problem is if I have 100 rows, when I Check header checkbox only some column checkboxes are checked i.e, only the rows that are displayed. When I scrolldown the remaining rows checkboxes are not checked. Here is my code:
List<Person> people = new ArrayList();
for (int i = 0; i < 1000; i++) {
people.add(i, new Person("Galileo Galilei", 1564));
}
CheckBox CheckBox1 = new CheckBox("All");
CheckBox1.setValue(false);
Grid<Person> grid = new Grid<>();
grid.setItems( people);
grid.addColumn(Person::getName).setCaption("Name");
grid.addColumn(Person::getYear).setCaption("Year of birth").setId("1");
grid.addComponentColumn(Person -> {
CheckBox chk=new CheckBox("Chk 2");
CheckBox1.addValueChangeListener(e->
chk.setValue(CheckBox1.getValue())
);
return chk;
}).setCaption("ch2").setId("CH2");
grid.getHeaderRow(0).getCell("CH2").setComponent( CheckBox1);
Well, for performance reasons, not all of the checkboxes are rendered from the start, as you'll see in the GIF below (right side, items flashing in violet), just the ones currently visible. And when you scroll, new items will be replacing the old ones, and checkboxes will be drawn for them. However their initial state will be uncheked, so the simplest solution is to set its initial state to the one of the master checkbox: CheckBox chk = new CheckBox("Chk 2", CheckBox1.getValue());.
Result:
Furthermore, looking at the code you might have a minor leak. Since the checkboxes are drawn each time you scroll a larger section, the code in grid.addComponentColumn will be called each time, and value change listeners will be added to the list on and on and on... because they're never unregistered. Take a look at the image below, after a few scrolls, I ended up with over 9000 of them:
To overcome this, you can un-register the listeners when the checkboxes are detached:
grid.addComponentColumn(Person -> {
CheckBox chk = new CheckBox("Chk 2", CheckBox1.getValue());
// save the registration info to unregister at a later time
Registration listenerRegistration = CheckBox1.addValueChangeListener(e -> chk.setValue(CheckBox1.getValue()));
// when the checkbox is detached, remove the listener
chk.addDetachListener(event -> listenerRegistration.remove());
return chk;
}).setCaption("ch2").setId("CH2");
Now the list contains just those who were not yet detached:
You could also extend data model by a boolean field "selected" or wrap it into a new class and there add the "selected" field. Then set/unset that field in the ValueChangeListener added to the CheckBox.
This will also take care of selecting all grid entries and not just the one rendered. You will just have to change "selected" in all you data model instances.
Another approach would be to use the ImageRenderer. Then you wouldn't have to deal with any listeners.
This assumes that your model has an attribute to hold the value of checked/selected.
ThemeResource resourceChecked = new ThemeResource("selected.gif");
ThemeResource resourceUnchecked = new ThemeResource("deselected.gif");
grid.addColumn(person -> person.getSelected() ? resourceChecked : resourceUnchecked,
new ImageRenderer<>(event -> {
Person person = event.getItem();
person.setSelected(!person.getSelected());
grid.getDataProvider().refreshItem(person);
grid.markAsDirty();
}));
I have a Jtable, whose first column uses a JComboBox as editor. The combobox model contains data objects fetched from a sql database.
If I manually enter a value inside the combobox and then leave the editor, the entered value is lost. This doens't happen if the value is selected from the popup, or if the JComboBox's model is instantiated with simple Strings instead of bean objects.
Note that I need to add row dinamically, but this seems irrelevant since the issue appears both in the default row and in the added rows.
This is a working NetBeans sample project that reproduces my issue: https://drive.google.com/open?id=0B89FsS48-Yy4V09YRVozRzJGMkk
Here is the relevant code:
public NewJFrame() {
initComponents();
//bean objects used to populate the combobox:
Item item1 = new Item("one", 1);
Item item2 = new Item("two", 2);
Item item3 = new Item("three", 3);
JComboBox<Item> comboBox = new JComboBox<>(new Item[]{item1, item2, item3});
comboBox.setEditable(true);
DefaultCellEditor defaultCellEditor = new DefaultCellEditor(comboBox);
defaultCellEditor.setClickCountToStart(1);
jTable1.getColumnModel().getColumn(0).setCellEditor(defaultCellEditor);
}
private void addRowButtonActionPerformed(java.awt.event.ActionEvent evt) {
((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{null, null});
}
Update: when the JComboBox in the table is populated via a model instead of the constructor like this,
items = new Item[]{item1, item2, item3};
JComboBox<Item> comboBox = new JComboBox<>();
comboBox.setModel(new DefaultComboBoxModel<>(items));
a manually inserted value is kept displayed, only if no selection has been made before; that is, if I first select a choice and then edit the choice, when leaving the combobox the previously selected item reappears.
None of the reported behaviours occur in a JComboBox outside the table, so this led me to think it's something related to the CellEditor.
Update 2: here's a bug report of this issue from the year 2000! They said they solved it back then but this is far from solved after 15 years.
I have three JCheckBox like following:
final JCheckBox c1 = new JCheckBox("A");
final JCheckBox c2 = new JCheckBox("B");
final JCheckBox c3 = new JCheckBox("C");
I make a group by ButtonGroup for this checkboxes like following:
final ButtonGroup bg = new ButtonGroup();
bg.add(c1);
bg.add(c2);
bg.add(c3);
I have a Button to display selected items into a label like following:
String SelectedItem="";
Enumeration<AbstractButton> items= bg.getElements();
while (items.hasMoreElements()) {
AbstractButton btn = items.nextElement();
if(btn.isSelected())
{
SelectedItem+=btn.getText()+",";
}
}
lblA.setText(SelectedItem);
this work fine , but i cann't select multiple check boxes in run time.
The purpose of ButtonGroup is multiple-exclusive selection. Do not create ButtonGroup only if you want to have a collection of your buttons. Instead of ButtonGroup use a standard collection like ArrayList.
List<JCheckBox> buttons = new ArrayList<>();
buttons.add(c1);
buttons.add(c2);
buttons.add(c3);
...
for ( JCheckbox checkbox : buttons ) {
if( checkbox.isSelected() )
{
SelectedItem += btn.getText() + ",";
}
}
Further notices: do updates (.setText) in Swing event thread (invokelater), remeber that it is better to create StringBuilder in such concatenation, but with UI component quantities like this, performance impact propably will be not noticeable.
From documentation:
Class ButtonGroup
This class is used to create a multiple-exclusion scope for a set of
buttons. Creating a set of buttons with the same ButtonGroup object
means that turning "on" one of those buttons turns off all other
buttons in the group.
That said, you probably are using the wrong class to do what you need, if you want to GROUP those checkboxes, put them in a panel, than you can work visibility, position and all other attributes with the panel instead of each checkbox.
Here is the link to documentation: Link
Connection connection = newConnection.createConnection();
Statement newStat = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet res = newStat.executeQuery("SELECT contactName FROM Contact WHERE accountName='"+m+"'");
Vector<String> temp = new Vector<String>();
//res.first();
while (res.next()){
temp.add(res.getString("contactName"));
}
newStat.close();
connection.close();
customerContactList = new JList(temp);
repaint();
I have a Jlist with account names, when an account is selected, on the side there is a button which has to be pressed for in order to call the code above.
The code is supposed to get contact names associated to that account and populate them into
the JList. This does not happen. The Jlist stays blank, i debugged and the vector temp does get 3 values and stores them into the new jlist, the problem is, JList does not refresh.
How can I make it refresh?
Thanks a lot and I appreciate any help.
Kunal
The new JList you created hasn't been added to any container, so you'd have to add it to the frame, just as the original one was, and then call "validate()" on the frame (always necessary when you add/remove components to a visible window.) But it would be better to call setListData() on the existing JList -- it would update right away, with less flashing around.
You can use a ListModel to manipulate the data inside the JList. And definitely not create new JLists at any step.
You have your JList bounded to your JFrame. Now you can get the data inside it using
JList list = new JList();
ListModel model = list.getModel();
and modify that model, then send the new model back:
DefaultListModel listModel = new DefaultListModel();
while (res.next()) {
listModel.addElement( res.getString("contactName") );
}
list.setModel(listModel);