Search code examples
javaswingjlistrenderer

Java formatting strings in JList


After hours of no luck with String.format()... I turn to you. Anyhow I have a JList that I populate with new entries here's the code:

private void addModule(final JList browse, final JList select){
    browse.addMouseListener(new MouseListener(){
        @Override
        public void mouseClicked(MouseEvent e) {
            String addable = browse.getSelectedValue().toString();
            if(e.getClickCount() == 2 && getSelectedTower() != null && addable.charAt(0) == ' '){
                String data[] = new EPTModule_Model().moduleData(addable.trim());
                String module = data[0];
                String module_cap = data[1];
                String module_cpu = data[2];
                struct.addElement("> " + module + "Capacitor:" + module_cap + "CPU:" + module_cpu);
                select.setModel(struct);
                setSelectedModules(1);
            } else if (e.getClickCount() == 2 && getSelectedTower() == null){
                new EPTEvent_Model().eventNoTowerSelected();
            }
        }
        @Override
        public void mousePressed(MouseEvent e) {}
        @Override
        public void mouseReleased(MouseEvent e) {}
        @Override
        public void mouseEntered(MouseEvent e) {}
        @Override
        public void mouseExited(MouseEvent e) {}
    });
}

Anyhow the thing is when I use my application now as I add new Elements to the list they are not all the same length so I get outputs like this:

  1. xxxxxxxxxxxxxxxxxxxx Capacitor: 555 Cpu: 10
  2. xxxxxxxxxx Capacitor: 555 Cpu: 10
  3. xxxxxxxxxxxxxxxxxxxxxxxxxxx Capacitor: 555 Cpu: 10

As you can see that is not very readable I want to output > Capacitor... to be aligned in same column regardless of xxxxxx string length. Anyhow the max length of xxxx strings is 47 chars if that helps.


Solution

  • Try this :

    struct.addElement(String.format("> %47s Capacitor: %s CPU: %s", module, module_cap, module_cpu));