henderjm@gmail.com schrieb:
> Does anyone know how to create a bunch of jCheckboxes based off of some
>
> XML file? I'm trying to add some checkboxes in a jPanel, but can't
> figure out how.
With two sentences, you've mentioned three problems and my crystal ball
is unable to tell me which is the one you want to have a solution for:
a) how to process an XML file
b) how to create instances of JCheckBox
c) how to add instances of JCheckBox to a container
So, below is a small (quick & dirty) example that creates instances of
JCheckBox based on the text content of an XML document's "Name" nodes.
The document is considered to be stored in a file "file.xml".
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class CheckBoxFactory {
private Document doc;
public CheckBoxFactory( InputStream xmlStream ) throws
ParserConfigurationException, org.xml.sax.SAXException,
IOException {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
doc = builder.parse( xmlStream );
}
public List<JCheckBox> getCheckBoxes() {
NodeList nodes = doc.getElementsByTagName("Name");
int n = nodes.getLength();
List<JCheckBox> result = new ArrayList<JCheckBox>(n);
for ( int i = 0; i < n; i++ ) {
Element name = (Element)nodes.item(i);
result.add( new JCheckBox(name.getTextContent()) );
}
return result;
}
public static final void main( String args[] ) throws Exception {
CheckBoxFactory factory = new CheckBoxFactory(
new FileInputStream("file.xml") );
JPanel panel = new JPanel( new GridLayout(0,1) );
for ( JCheckBox cb : factory.getCheckBoxes() )
panel.add( cb );
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
frame.getContentPane().add( panel, BorderLayout.NORTH );
frame.pack();
frame.setVisible( true );
}
}
Bye
Michael