java-org.hwo.ui/src/org/hwo/ui/JOptionGroup.java

129 lines
2.3 KiB
Java

package org.hwo.ui;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import javax.swing.GroupLayout;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class JOptionGroup extends JComponent {
JCheckBox checkBoxes[];
private String[] options;
private String[] selectedOptions;
public JOptionGroup()
{
FlowLayout layout = new FlowLayout(FlowLayout.LEADING);
setLayout(layout);
options = new String[0];
checkBoxes = new JCheckBox[0];
setPreferredSize(new Dimension(270, 29));
}
public String[] getOptions() {
return options;
}
public void setOptions(String[] options) {
this.options = options;
if (options == null)
options = new String[0];
rebuildOptions();
if (selectedOptions != null)
setSelectedOptions(selectedOptions);
}
private void rebuildOptions()
{
for (JCheckBox cb:checkBoxes)
{
remove(cb);
}
checkBoxes = new JCheckBox[ options.length ];
for (int n=0; n < options.length; n++)
{
checkBoxes[n] = new JCheckBox();
checkBoxes[n].setText(options[n]);
add(checkBoxes[n]);
}
invalidate();
repaint();
}
public int getOptionIndex(String option)
{
for (int n=0; n < options.length; n++)
{
if (options[n].equals(option))
return n;
}
return -1;
}
public Boolean isOptionSelected(String option)
{
int no = getOptionIndex(option);
if (no >= 0)
{
return checkBoxes[no].isSelected();
}
return false;
}
public void selectOption(String option)
{
int no = getOptionIndex(option);
if (no >= 0)
{
checkBoxes[no].setSelected(true);
}
}
public void unselectOption(String option)
{
int no = getOptionIndex(option);
if (no >= 0)
{
checkBoxes[no].setSelected(false);
}
}
public String[] getSelectedOptions()
{
ArrayList<String> ol = new ArrayList<String>();
for (int n=0; n < options.length; n++)
{
if (checkBoxes[n].isSelected())
ol.add(options[n]);
}
return ol.toArray(new String[0]);
}
public void setSelectedOptions(String[] selectedOptions)
{
this.selectedOptions = selectedOptions;
for (int n=0; n < options.length; n++)
checkBoxes[n].setSelected(false);
for (String option:selectedOptions)
selectOption(option);
}
}