select many Checkbox in a checkboxgroup java swing - java

I am working on a Jframe netbeans IDE basically i drag and drop thing in the form i want to make a group of checkboxes at least two groups in one frame and each group has many checkboxes i want to select multiple checkbox in each group and return the value of checked boxes i have read that button group is not applicable in this situation since button group will only have one selection. Any code snippet or idea on how to do this is much appreciated.
UPDATE
Found this sample this is how i want my checkbox to behave only i dont want to put them in table plus there is no table component in netbeans IDE i can drag for this purpose any idea on how to do this is much appreciated

I agree with Trashgod, a JTable is probably a good place to start, another option is to roll your own...
Each "column" is it's own component and allows you to select multiple options, but only within the context of that "group"
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(new CheckBoxGroup(new String[]{"Bananas", "Oranages", "Apples", "Pears"}));
frame.add(new CheckBoxGroup(new String[]{"Learn Archery", "Float in the dead sea", "Swing with a whale shark", "Sail the greek islands", "Go skydiving", "Dance in the rain", "Cycle through the Netherlands"}));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CheckBoxGroup extends JPanel {
private JCheckBox all;
private List<JCheckBox> checkBoxes;
public CheckBoxGroup(String... options) {
checkBoxes = new ArrayList<>(25);
setLayout(new BorderLayout());
JPanel header = new JPanel(new FlowLayout(FlowLayout.LEFT, 1, 1));
all = new JCheckBox("Select All...");
all.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox cb : checkBoxes) {
cb.setSelected(all.isSelected());
}
}
});
header.add(all);
add(header, BorderLayout.NORTH);
JPanel content = new ScrollablePane(new GridBagLayout());
content.setBackground(UIManager.getColor("List.background"));
if (options.length > 0) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1;
for (int index = 0; index < options.length - 1; index++) {
JCheckBox cb = new JCheckBox(options[index]);
cb.setOpaque(false);
checkBoxes.add(cb);
content.add(cb, gbc);
}
JCheckBox cb = new JCheckBox(options[options.length - 1]);
cb.setOpaque(false);
checkBoxes.add(cb);
gbc.weighty = 1;
content.add(cb, gbc);
}
add(new JScrollPane(content));
}
public class ScrollablePane extends JPanel implements Scrollable {
public ScrollablePane(LayoutManager layout) {
super(layout);
}
public ScrollablePane() {
}
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(100, 100);
}
#Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 32;
}
#Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 32;
}
#Override
public boolean getScrollableTracksViewportWidth() {
boolean track = false;
Container parent = getParent();
if (parent instanceof JViewport) {
JViewport vp = (JViewport) parent;
track = vp.getWidth() > getPreferredSize().width;
}
return track;
}
#Override
public boolean getScrollableTracksViewportHeight() {
boolean track = false;
Container parent = getParent();
if (parent instanceof JViewport) {
JViewport vp = (JViewport) parent;
track = vp.getHeight() > getPreferredSize().height;
}
return track;
}
}
}
}
What it doesn't do is return a list of selected items, but how hard would it be to iterate over the checkBoxes List, check to see if the item is selected or not, extract it's text and add it to another List and return the result...?

Related

Jlabel change color on mouse click Java

I am adding multiple Jlabel using for loop. What I want is on mouse click, the color of the selected JLabel should change and set to the default color on click of anotherJLabel.
Since you changed the state of the label, you need someway to change it back. The simplest solution is to maintain a reference to the last label that was changed and when the new label is clicked, reset it's state
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
HighlightMouseListener hml = new HighlightMouseListener();
for (int index = 0; index < 10; index++) {
JLabel label = new JLabel("Hello " + index);
label.addMouseListener(hml);
add(label, gbc);
}
}
}
public class HighlightMouseListener extends MouseAdapter {
private JLabel previous;
#Override
public void mouseClicked(MouseEvent e) {
Component source = e.getComponent();
if (!(source instanceof JLabel)) {
return;
}
JLabel label = (JLabel) source;
if (previous != null) {
previous.setBackground(null);
previous.setForeground(null);
previous.setOpaque(false);
}
previous = label;
label.setForeground(Color.WHITE);
label.setBackground(Color.BLUE);
label.setOpaque(true);
}
}
}
I still wonder if a JList would be a better and simpler solution, but since I don't know what you're doing, it's all I can do

Drag and Drop from JButton to JComponent in Java

I searched on the internet for examples how to Drag and Drop JButtons to an Object but I could not make it work.
What my program does, is that when I click on a button, the object updated a field (with a selectedobject.setField()). I want to be able to do this not by clicking, but by dragging the JButton.
How can I do this ?
I found this, and I tried to put in my code:
btn.setTransferHandler(new ImageHandler());
btn.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
});
I took the ImageHandler class from here.
Drag'n'drop is a fun bag of crunchy, munchy carrots...not helped by the fact that there is a "core" API and the newer "transfer" API, so it's really easy to get confused
The following example uses the "transfer" API and basically transfers a String value from a button to a JLabel.
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(1, 2));
add(createLeftPanel());
add(createRightPanel());
}
protected JPanel createLeftPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
for (int index = 0; index < 10; index++) {
JButton btn = new JButton(Integer.toString(index + 1));
panel.add(btn, gbc);
btn.setTransferHandler(new ValueExportTransferHandler(Integer.toString(index + 1)));
btn.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
JButton button = (JButton) e.getSource();
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
}
});
}
return panel;
}
protected JPanel createRightPanel() {
JPanel panel = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Drop in");
label.setBorder(new CompoundBorder(new LineBorder(Color.DARK_GRAY), new EmptyBorder(20, 20, 20, 20)));
label.setTransferHandler(new ValueImportTransferHandler());
panel.add(label);
return panel;
}
}
public static class ValueExportTransferHandler extends TransferHandler {
public static final DataFlavor SUPPORTED_DATE_FLAVOR = DataFlavor.stringFlavor;
private String value;
public ValueExportTransferHandler(String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_COPY_OR_MOVE;
}
#Override
protected Transferable createTransferable(JComponent c) {
Transferable t = new StringSelection(getValue());
return t;
}
#Override
protected void exportDone(JComponent source, Transferable data, int action) {
super.exportDone(source, data, action);
// Decide what to do after the drop has been accepted
}
}
public static class ValueImportTransferHandler extends TransferHandler {
public static final DataFlavor SUPPORTED_DATE_FLAVOR = DataFlavor.stringFlavor;
public ValueImportTransferHandler() {
}
#Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(SUPPORTED_DATE_FLAVOR);
}
#Override
public boolean importData(TransferHandler.TransferSupport support) {
boolean accept = false;
if (canImport(support)) {
try {
Transferable t = support.getTransferable();
Object value = t.getTransferData(SUPPORTED_DATE_FLAVOR);
if (value instanceof String) {
Component component = support.getComponent();
if (component instanceof JLabel) {
((JLabel) component).setText(value.toString());
accept = true;
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
return accept;
}
}
}
I've gone out my way to separate the TransferHandlers allowing for a "drag" and "drop" version. You don't "have" to do this and you "could" use a single TransferHandler to perform both operations, that's up to you.
You will have to modify the ValueExportTransferHandler to accept different values and modify the SUPPORTED_DATE_FLAVOR accordingingly, but those are the basics
You could also have a look at Drag and Drop custom object from JList into JLabel as another example...

how to insert more than one jComponents into a cell in a jTable

I have a jTable which is populating according to my requirement . I want to add two comboboxes into all the cells in one column. So can anyone help me on this... ![here is my table ][1]
[1]: http://i.stack.imgur.com/nC9RL.jpg I need to add two comboboxes into all the rows of 1 st column. I did my coding into CREATE TABLE button which u can see in the image. here is my code so far : | |
int row=0;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
row=Integer.parseInt(jTextField2.getText());
row=row-1;
DefaultTableModel dtm =(DefaultTableModel) jTable1.getModel();
TableColumn sportColumn = jTable1.getColumnModel().getColumn(1);
JComboBox subject= new JComboBox();
box.addItem("DDD");
box.addItem("CCC");
JComboBox teacher= new JComboBox();
box1.addItem("AAA");
box1.addItem("FFF");
JPanel jPanel = new JPanel();
GroupLayout gl= new GroupLayout(jPanel);
jPanel.setLayout(gl);
jPanel.add(box);
jPanel.add(box1);
dtm.setRowCount(0);
dtm.setRowCount(Integer.parseInt(jTextField1.getText()));
for (int i = 0; i < dtm.getRowCount(); i++) {
row++;
dtm.setValueAt(String.valueOf(row), i, 0);
sportColumn.setCellRenderer(
(TableCellRenderer) new DefaultTableCellRenderer()
.getTableCellRendererComponent(
jTable1, jPanel, true, true, i, 1));
}
}
jButton1===> create table Button / jTextField2===> number starts with / jTextField1===>number of rows
Caverts:
I think this is a crazy idea, personally. If your cell represents a compound object, then I'd be thinking about using a dialog or some other means, but that's me.
Personally, I think this is going to blow up in your face...
Example
The concepts presented are all based on the information from How to use Tables
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractCellEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumnModel;
public class Enrolement {
public static void main(String[] args) {
new Enrolement();
}
public Enrolement() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Subject"}, 10);
JTable tbl = new JTable(model);
TableColumnModel columnModel = tbl.getColumnModel();
columnModel.getColumn(0).setCellEditor(new SubjectTableCellEditor());
tbl.setRowHeight(columnModel.getColumn(0).getCellEditor().getTableCellEditorComponent(tbl, "Astronomy/Aurora Sinistra", true, 0, 0).getPreferredSize().height);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tbl));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SubjectTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private JComboBox subject;
private JComboBox teacher;
private JPanel editor;
private Map<String, String[]> subjectTeachers = new HashMap<>(25);
public SubjectTableCellEditor() {
subjectTeachers.put("Astronomy", new String[]{"Aurora Sinistra"});
subjectTeachers.put("Charms", new String[]{"Filius Flitwick"});
subjectTeachers.put("Dark Arts", new String[]{"Igor Karkaroff", "Amycus Carrow"});
subjectTeachers.put("Defence Against the Dark Arts", new String[]{"Defence Against the Dark Arts",
"Quirinus Quirrell",
"Gilderoy Lockhart",
"Remus Lupin",
"Bartemius Crouch Jr.",
"Dolores Umbridge",
"Severus Snape",
"Amycus Carrow"});
subjectTeachers.put("Flying", new String[]{"Rolanda Hooch"});
subjectTeachers.put("Herbology", new String[]{"Herbert Beery",
"Pomona Sprout",
"Neville Longbottom"});
subjectTeachers.put("History of Magic", new String[]{"Professor Cuthbert Binns"});
subjectTeachers.put("Potions", new String[]{"Severus Snape",
"Horace Slughorn"});
subjectTeachers.put("Transfiguration", new String[]{"Minerva McGonagall",
"Albus Dumbledore"});
subject = new JComboBox(new String[]{
"Astronomy",
"Charms",
"Dark Arts",
"Defence Against the Dark Arts",
"Flying",
"Herbology",
"History of Magic",
"Potions",
"Transfiguration"
});
teacher = new JComboBox();
editor = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
editor.add(subject, gbc);
editor.add(teacher, gbc);
subject.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
teacher.setModel(new DefaultComboBoxModel(subjectTeachers.get(subject.getSelectedItem())));
}
});
}
#Override
public Object getCellEditorValue() {
return subject.getSelectedItem() + "/" + teacher.getSelectedItem();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof String) {
String parts[] = value.toString().split("/");
subject.setSelectedItem(parts[0]);
teacher.setSelectedItem(parts[1]);
}
editor.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
return editor;
}
}
}

Is it possible to use a JSlider controlling multiple JTextfield?

I tried to use a JSlider to set text in three JTextFields.
My condition is the slider should work for textfield_1, only when a textfield_1 get its focus, similarly for the other two textfields.
When I tried to use the same slider with other textfield, only the first text field values getting changed.
Expecting valuable suggestions Thanks in Advance.
JSlider slider;
JTextField tf;
tf.addFocusListener(new FoucusListener(){
public void foucusGained(FocusEvent fe){
slider.addChangeListener(new ChangeListener()){
public void stateChanged(ChangeEvent ce){
JSlider slider =(JSlider)ce.getSource();
if(slider.getValueisAdjusting())
tf.setText(String.valueOf(slider.getValue()))
}
});
});
The basic idea is you need to know what field was last selected. The problem is, when you select the slider, it will fire a focus gained event...
The simplest idea would be to use a FocusListener registered only to the text fields and maintain a reference to the last field selected.
When the slider changes, you would simply interact with the last selected field (if it's not null)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderControl {
public static void main(String[] args) {
new SliderControl();
}
public SliderControl() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JSlider slider;
private JTextField[] fields;
private JTextField selectedField;
public TestPane() {
setLayout(new GridBagLayout());
fields = new JTextField[3];
FocusHandler focusHandler = new FocusHandler();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < 3; index++) {
fields[index] = new JTextField(3);
fields[index].addFocusListener(focusHandler);
add(fields[index], gbc);
gbc.gridy++;
}
gbc.fill = GridBagConstraints.HORIZONTAL;
slider = new JSlider();
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (selectedField != null) {
selectedField.setText(String.valueOf(slider.getValue()));
}
}
});
add(slider, gbc);
}
protected class FocusHandler extends FocusAdapter {
#Override
public void focusGained(FocusEvent e) {
if (e.getComponent() instanceof JTextField) {
selectedField = (JTextField) e.getComponent();
}
}
}
}
}

How is JSpinner different than other swing components?

I have a method that can recursively enable/disable all components within a JPanel. There are also exception lists. So I can do the following
Disable all components in panel1 except for textfield1, textfield3 who should be enabled.
Enable all components in panel2 except for button2, label3 who should be disabled.
Here is a SSCCE that does exactly that:
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JPanel panel = new JPanel(new GridLayout(3, 3));
final JTextField textfield = new JTextField("asdf");
final JButton button = new JButton("asdf");
final JCheckBox checkbox = new JCheckBox("asdf");
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1));
final JLabel label = new JLabel("asdf");
panel.add(textfield);
panel.add(button);
panel.add(checkbox);
panel.add(spinner);
panel.add(label);
// fill in some random stuff
for (int i = 0; i < 4; i++)
panel.add(new JLabel("asdf"));
frame.setContentPane(panel);
frame.setSize(300, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Thread(new Runnable() {
#Override
public void run() {
boolean toggle = true;
while (true) {
toggle = !toggle;
Set<Component> enableList = new HashSet<Component>();
Set<Component> disableList = new HashSet<Component>();
enableList.add(textfield);
enableList.add(spinner);
disableList.add(checkbox);
setEnableAllRec(panel, toggle, disableList, enableList);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}).start();
frame.setVisible(true);
}
public static void setEnableAllRec(Container root, boolean defaultState, Set<Component> disableList, Set<Component> enableList) {
if (root == null) return;
for (Component c : root.getComponents()) {
if (disableList != null && disableList.contains(c)) {
c.setEnabled(false);
disableList.remove(c);
} else if (enableList != null && enableList.contains(c)) {
c.setEnabled(true);
enableList.remove(c);
} else c.setEnabled(defaultState);
if (c instanceof Container) setEnableAllRec((Container) c, defaultState, disableList, enableList);
}
}
}
The SSCCE sets all components every second to enable/disable alternatingly. Except for some components that should always be enabled and some that should always be disabled. That works extremely well except for the JSpinner. It gets detected as a component but can not be found in the list (and therefore is not handled as a special case). All other swing components that I have tried are working as expected.
Can you tell me whats wrong with JSpinner?
I hope the SSCCE is not too confusing... ;)
Simply because a JSpinner contains other components such as 2 buttons and an editor (see the code of javax.swing.plaf.basic.BasicSpinnerUI) and you go recursively on all containers, thus, also on contained components of the JSpinner.
Btw, your Thread is violating the Swing-EDT. You should rather perform that in a Swing Timer
The solution is easy:
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JPanel panel = new JPanel(new GridLayout(3, 3));
final JTextField textfield = new JTextField("asdf");
final JButton button = new JButton("asdf");
final JCheckBox checkbox = new JCheckBox("asdf");
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1));
final JLabel label = new JLabel("asdf");
panel.add(textfield);
panel.add(button);
panel.add(checkbox);
panel.add(spinner);
panel.add(label);
// fill in some random stuff
for (int i = 0; i < 4; i++) {
panel.add(new JLabel("asdf"));
}
frame.setContentPane(panel);
frame.setSize(300, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Thread(new Runnable() {
#Override
public void run() {
boolean toggle = true;
while (true) {
toggle = !toggle;
Set<Component> enableList = new HashSet<Component>();
Set<Component> disableList = new HashSet<Component>();
enableList.add(textfield);
enableList.add(spinner);
disableList.add(checkbox);
setEnableAllRec(panel, toggle, disableList, enableList);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}).start();
frame.setVisible(true);
}
public static void setEnableAllRec(Container root, boolean defaultState, Set<Component> disableList, Set<Component> enableList) {
if (root == null) {
return;
}
for (Component c : root.getComponents()) {
if (disableList != null && disableList.contains(c)) {
c.setEnabled(false);
disableList.remove(c);
} else if (enableList != null && enableList.contains(c)) {
c.setEnabled(true);
enableList.remove(c);
} else {
c.setEnabled(defaultState);
if (c instanceof Container) {
setEnableAllRec((Container) c, defaultState, disableList, enableList);
}
}
}
}
}

Categories

Resources