Combobox吃空格,内容看起来不对齐

时间:2015-04-09 17:02:07

标签: java arrays swing format jcombobox

我尝试在一行中填充一个带有ip地址,端口和调试状态(true或false)的jcombobox。如果项目的长度不同,它们在jcomboxbox中显示为无组织。我希望它能够协调一致。

控制台中的输出(以及jcombobox中的所需输出):

   136.18.151.1   8735   true
  200.200.20.21  32310   true
  300.34.30.100   2138  false
 400.400.400.10  31230  false

jcomboxbox中的输出:

   136.18.151.1   8735   true
    200.200.20.21  32310  true
  300.34.30.100   2138  false
   400.400.400.100  31230  false

基本上我正在读取XML文件,然后将每个项目保存在各自的列表中。

public List<String> ipList = new ArrayList<String>();
public List<String> portList = new ArrayList<String>();
public List<String> debugList = new ArrayList<String>();

然后我从数组中获取相同索引中的每个项目,将其放入一个字符串中,然后连接字符串并将连接的字符串放入常规字符串数组中。

public class myJAXB {

 public String[] populateArray() {

        int size = ipList.size();
        String[] connsList = new String[size];
        String tempIp, tempPort, tempDebug;


        for (int i = 0; i < size; i++) {
            tempIp = ipList.get(i);

            // here is the default jdk method (has not worked)
            tempIp = String.format("15%s", tempIp);

            // here im using the apache commons lib (has not worked)
            tempIp = StringUtils.leftPad(tempIp,15);

            //this is a method I created (has not worked)
            tempIp = formatString(tempIp, 'i');

            //same steps for the portList and debugList.. omitted for brevity 

            //save strings to string array, I suspect the error could be here? When joining strings maybe?
            connsList[i] = tempIp + tempPort +  tempDebug;

            //print to console to check output
            System.out.println("" + connsList[i]);
        }


        return connsList;
    }
}

这是我的formatString方法

public class myJAXB {

 public String formatString(String string, char type) {
        StringBuilder sb = new StringBuilder();

        //desired length of string
        int padnum = 0;

        //actual length of string
        int length=0;

        //if ip address
        if (type == 'i') {
            padnum = 15;
        }

        //if port or debug
        if (type == 'p' || type == 'd') {
            padnum = 7;
        }

        length = string.length();

        char[] pad = new char[padnum - length];

        //fill char array with empty space
        Arrays.fill(pad, ' ');

        return sb.append(pad).append(string).toString();
    }

}

最后我打电话来创建和填充jcombobox

jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(jax.populateArray()));

在创建jcombobox时也尝试使其对齐但是也没有工作..

// ((JLabel)jComboBox1.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);        
// ((JLabel)jComboBox1.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

我注意到在调试时确实插入了空格,最终字符串数组的内容应该是这样的,但当它们被放入jcombobox时它会改变!

非常感谢任何帮助。干杯!

0 个答案:

没有答案