A Transformer can be used to write a the XML for a DOM Document to a file. As the name implies a Transformer transforms a Source object into a Result, in this case the Source is the DOM Document, and the Result is an XML file.
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Result result = new StreamResult(new File(xmlOutputFilePath));
Source source = new DOMSource(document);
transformer.transform(source, result);
written by objects
\\ tags: Document, DOM, Transformer
To restrict the number of characters that the user can enter into a text field can be achieved by either using a JFormattedTextField or using a custom Document with any JTextComponent.
To implement this using a JFormattedTextFiled is simply a matter of specifying the appropriate MaskFormatter to meet your requiremenets.
JTextField field = new JFormattedTextField(new MaskFormatter("***"));
The following class gives an example of how a custom Document can be implemented for use in any text component.
public class FixedSizeDocument extends PlainDocument
{
private int max = 10;
public FixedSizeDocument(int max)
{
this.max = max;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
// check string being inserted does not exceed max length
if (getLength()+str.length()>max)
{
// If it does, then truncate it
str = str.substring(0, max - getLength());
}
super.insertString(offs, str, a);
}
}
You can then use this class with your JTextField for example using the following
field.setDocument(new FixedSizeDocument(5));
written by objects
\\ tags: Document, JFormattedTextField, JTextComponent, JTextField, MaskFormatter, PlainDocument
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
// or if you need to specify an encoding explitily
// Document document = builder.parse(
// new InputStreamReader(new FileInputStream(file), encoding));
written by objects
\\ tags: Document, DOM, file, load
Recent Comments