Swing JList font width
I am making a java program with produces a recept in a listbox, it will display the number of items, the item name and the price of the item. I need to pad the string so that the name is ruffly in the middle and the number of items and the cost are at ether side. Ca开发者_高级运维n you find the with in pixels of the strings then I can calculate the number of spaces needed to acheive the desired format. Thanks
This is how you get the width of a string:
Graphics2D g2d = (Graphics2D)g;
FontMetrics fontMetrics = g2d.getFontMetrics();
int width = fontMetrics.stringWidth("aString");
int height = fontMetrics.getHeight();
...
But, as I read your question again I tought, why not use the ListCellRenderer in JList? It works as you want:
http://img189.imageshack.us/img189/7509/jlistexample.jpg
And here is the code for it:
public static void main(String... args) {
JFrame frame = new JFrame("Test");
JList list = new JList(new String[] {
"Hello", "World!", "as", "we", "know", "it" });
list.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JPanel panel = new JPanel(new GridBagLayout());
if (isSelected)
panel.setBackground(Color.LIGHT_GRAY);
panel.setBorder(BorderFactory.createMatteBorder(
index == 0 ? 1 : 0, 1, 1, 1, Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4,4,4,4);
// index
gbc.weightx = 0;
panel.add(new JLabel("" + index), gbc);
// "name"
gbc.weightx = 1;
panel.add(new JLabel("" + value), gbc);
// cost
gbc.weightx = 0;
String cost = String.format("$%.2f", Math.random() * 100);
panel.add(new JLabel(cost), gbc);
return panel;
}
});
frame.add(list);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
精彩评论