Frage

I want to set the background color in my JList and want to give some space between every list and I also want to increase the font size.

How can I do this? My code is given below

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();

    }
}

How can I achieve my desired output?

War es hilfreich?

Lösung

Use a ListCellRenderer... See Customize Your JList Display for details.

enter image description here

This answer shows how to adjust the font of a renderer. That is a combo box of course, but combos and lists both use renderers.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top