by admin

Increasing size of combo box popup in Java

November 7, 2015 in Java, Programming, Programming Languages, Source Code, Tips & Tricks by admin

java-small-logoRecently I had a strange issue: how to increase the size of JComboBox popup without increasing the size of JComboBox itself, specifically displaying during selection options which are longer than the combo box itself. After various unsuccessful approaches, I’ve found a neat solution posted by Rob Camick in 2010 on Java Tips Webbog, in form of a class which acts as a PopupMenuListerner. This class itself allows even more functionalities than I hoped for, and also works neatly in java 8’s Swing. This is how a JComboBox with resized popup would look like:

For a longer description and the class’s usage and source code, follow the original article here.

by admin

Validating XML node against a XSD schema

February 12, 2013 in Code Snippets, Tutorial by admin

Sometimes you need to make sure a part of the xml document (more precisely a node and all node’s children) are valid according to a given schema. So how this can be done, as XML validators tend to work on document basis (there seems to be something called XML fragments, but haven’t yet found a way to validate the nodes using xml fragments) ?

The workflow is simple:

  1. load the xsd file we want to validate against. For this I’ll use the handy class which searches the classpath for the given resource.
  2. transform the node into xml document.
  3. validate the document against the schema.

For transforming the xml node to document, first we’ll transform it into a string, with this handy method found here:

public static String xmlToString(Node node)
{
    try
    {
        Source source = new DOMSource(node);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    }
    catch (TransformerConfigurationException e)
    {
        e.printStackTrace();
    }
    catch (TransformerException e)
    {
        e.printStackTrace();
    }

    return null;
}

then we’ll use this string as a stream to create the document from and validate against the schema as bellow:

StringReader r = new StringReader(xmlToString(node));
validator.validate(new StreamSource(r));

Source: here

 
Skip to toolbar