1

Below is my code which creates a list in Swing. As I click on the list it changes its color, but I need text to be displayed instead of color change in background; or when I click on list item, it need to display some text in separate window/within that window. Please help me regarding this. Below is my code which changes color on click.

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;

public class JListDemo extends JFrame {

    JList list;
    String[] listColorNames = {"black", "blue", "green", "yellow",
        "white"};
    Color[] listColorValues = {Color.BLACK, Color.BLUE, Color.GREEN,
        Color.YELLOW, Color.WHITE};
    Container contentpane;

    public JListDemo() {
        super("List Source Demo");
        contentpane = getContentPane();
        contentpane.setLayout(new FlowLayout());
        list = new JList(listColorNames);
        list.setSelectedIndex(0);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        contentpane.add(new JScrollPane(list));
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                contentpane.setBackground(listColorValues[list
                    .getSelectedIndex()]);
            }
        });
        setSize(200, 200);
        setVisible(true);
    }

    public static void main(String[] args) {
        JListDemo test = new JListDemo();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 2
    Your code works. What text should be displayed? Where? – trashgod Mar 14 '13 at 10:32
  • 1
    You'll get answers more easily if you prepare your question a little more. As well as being more precise about what you want to do, you should let us know that you've read the Swing tutorial. We won't do your reading for you, but we can help out if there's something in the tutorial that you didn't understand. – Andrew Spencer Mar 14 '13 at 10:54

1 Answers1

0

I think the following code snippet will produce the desired effect. You should enlarge the frame to see the effect.

contentpane.add(new JLabel(listColorNames[list.getSelectedIndex()]),BorderLayout.WEST);

You can add a JPanel to see more flexible result.

MattAllegro
  • 6,455
  • 5
  • 45
  • 52