Creating checkboxes in Java Swing application
I am creating this application to communicate the servlet by sending the selected units, if there is any changes in unit master server sends those units in the form of map with null values. From the desktop I need to get data from the server for only selected units. Initially server sends all the units and associated data to the desktop app, after selection at desktop again we need to connect to server to get data. For that I need show the checkboxes with the names which are there in map.
How to create checkboxes in Java Swing application with Map keys as their 开发者_Python百科names. Assume initially from the server
Map<String, String> m1 = new HashMap<String, String>();
m1.put("091","091");
m1.put("061","061");
m1.put("001","001");
m1.put("032","031");
After selection at desk application, it should be
Map<String, String> m1 = new HashMap<String, String>();
m1.put("091","091");
m1.put("061",null);
m1.put("001",null);
m1.put("032","031");
With res. to key and value pair of map I want to create the checkboxes where key is the name of the checkbox and value is to select that checkbox. If key contains a value (not null) then while creating that checkbox it should be selected. The map is going to be changed dynamically and creating checkboxes should be added to the JDialog. At the end of the selection I need to construct the map and I want to send that to the server.
I always start with the examples in the tutorial on Check Boxes. If that's not what you mean, can edit your question?
Create an array of JCheckBoxs
, the size of the array should be the size of m1
. Iterate over m1
and initialize the JCheckBoxes
accordingly, for example if entry is the current entry (in your iteration), cbArr is the array of checkboxes and i initialized to 0 before the start of the loop:
cbArr[i] = new JCheckBox(entry.getKey());
if (entry.getValue() != null)
{
cbArr[i].setSelected(true);
}
else
{
cbArr[i].setSelected(false);
}
yourPanel.add(cbArr[i++]);
This is the basic, to create the updated HashMap (to send to server) iterate over the array of CheckBoxes and insert key as current name of the check box, and value depending if the checkbox is selected or not.
Hash<String,String> m2 = new HashMap<String,String>();
for (int i = 0; i < cbArr.length; i++)
{
m2.put(cbArr[i].getText(), cbArr[i].isSelected() ? cbArr[i].getText() : null);
}
精彩评论