如何在JList中设置背景颜色和字体大小?

时间:2014-03-07 10:46:30

标签: java swing fonts colors jlist

我想在JList中设置背景颜色,并希望在每个列表之间留出一些空间,我也想增加字体大小。

我该怎么做?我的代码如下:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;

/* ListDemo.java requires no other files. */
public class ListDemo extends JPanel
                      implements ListSelectionListener {
    private JList list;
    private DefaultListModel listModel;


    public ListDemo() {
        super(new BorderLayout());

        listModel = new DefaultListModel();
        listModel.addElement("Jomerdhpur                                                                                                                                                                                                                                                                                                                                                                                                                      Barmer");
        listModel.addElement("John Smith");
        listModel.addElement("Kathy Green");
         listModel.addElement("Jane Doe");
        listModel.addElement("John Smith");
        listModel.addElement("Kathy Green");

        //Create the list and put it in a scroll pane.
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        list.setVisibleRowCount(5);
        JScrollPane listScrollPane = new JScrollPane(list);
          add(listScrollPane, BorderLayout.CENTER);
      //  add(buttonPane, BorderLayout.PAGE_END);
    }

    public void valueChanged(ListSelectionEvent e) {

    }


    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ListDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ListDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        frame.setBackground(Color.yellow);


        frame.pack();
        frame.setVisible(true);
    }
   public static void main(String[] args) {

                createAndShowGUI();

    }
}

如何实现所需的输出?

1 个答案:

答案 0 :(得分:3)

使用ListCellRenderer ...有关详细信息,请参阅Customize Your JList Display

enter image description here

This answer显示了如何调整渲染器的字体。当然这是一个组合框,但组合和列表都使用渲染器。