How do you have JList display user defined element

How do you have JList display the element you define?

I tried:

list.setSelectedIndex( 1 );

list.ensureIndexIsVisible(1);

because I want the element at index[1] in the list to be displayed when the GUI opens. It always defaults to element [0] (1st element).

So if I have

String[] colors = {blue, red, yellow};

when the GUI opens, I want "red" to appear in the JList, but blue is always displayed...

[448 byte] By [ponchoa] at [2007-11-27 9:25:37]
# 1
Where in your code do you call those methods?
hunter9000a at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 2

This is what I did in the GUI class for the setup

int index = getFacilityIndex( SenListHelpers.getFacility(array, lineCount), SenListArraySetUp.facilities );

System.out.println("Index" + index);

list.setSelectedValue(SenListArraySetUp.facilities[index], true);

list.setSelectedIndex( 1 );

//list.setSelectedIndex( getFacilityIndex(lineCount) );

list.ensureIndexIsVisible(index);

list.setVisibleRowCount(1);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

//contentpane

spacerPanel.add(new JScrollPane(list));

ponchoa at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 3

Swing related questions should be posted in the Swing forum.

If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",

see http://homepage1.nifty.com/algafield/sscce.html,

that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

Don't forget to use the "Code Formatting Tags",

see http://forum.java.sun.com/help.jspa?sec=formatting,

so the posted code retains its original formatting.

camickra at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 4

Here is a small working program showing my problem....

String facilities[] = {"blue","green", "yellow"};

public correctOfficerGUI()

{

//JFrame

f = new JFrame("Add Officer");

//int x = f.DoModal();

// Make a panel to hold the demo 揻orm", then

// add it to the top of the frame抯 content pane

//JPanel

form = new JPanel();

f.getContentPane().setLayout(new BorderLayout());

f.getContentPane().add(form, BorderLayout.NORTH);

// Set the form panel抯 layout to GridBagLayout

// and create a FormUtility to add things to it.

form.setLayout(new GridBagLayout());

JPanel spacerPanel = new JPanel();

spacerPanel.setLayout(new BorderLayout());

final JList list = new JList(facilities);

int index = 2;

list.setSelectedIndex( 1 );

list.setVisibleRowCount(1);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

//contentpane

form.add(new JScrollPane(list));

JButton addButton = new JButton("Add");

form.add(addButton);

//addButton.add(

addButton.addActionListener(

new ActionListener()

{

public void actionPerformed( ActionEvent actionEvent )//valueChanged(ListSelectionEvent e)

{

//f.DoModal();

System.out.println("********************************************");

JOptionPane.showMessageDialog(null, "The Officer has been Added.");

}

}

);

// Add an little padding around the form

form.setBorder(new EmptyBorder(2, 2, 2, 2));

f.setSize(300, 300);//230);

f.setVisible(true);

}

public static void main(String[] args)

{

correctOfficerGUI test = new correctOfficerGUI();

test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

ponchoa at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 5
> Here is a small working program showing my problem....How do I copy, paste and compile that. There are no import statements. There is no class statement.
camickra at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 6

Sorry, that must've been cut off, here it is...

What I want it to do is open and I want "green" to be the only element showing in the JList...

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import java.awt.Container;

import javax.swing.JOptionPane;

import java.lang.Object;

import java.awt.event.*;

import java.awt.Component;

import javax.swing.JOptionPane;

import java.awt.BorderLayout;

//import java.awt.Container;

import java.awt.Dimension;

import java.awt.Rectangle;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

import javax.swing.event.ListSelectionEvent;

import javax.swing.event.ListSelectionListener;

//import javax.media.jai.JAI;

//import javax.media.jai.PlanarImage;

import javax.swing.BorderFactory;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JComponent;

import javax.swing.SpringLayout;

import javax.swing.border.BevelBorder;

/**

* Simple applications for demonstrating the use of FormUtility

* to hide the details of creating a form layout with

* GridBagLayout.

* <P>

* Philip Isenhour - 060628 - http://javatechniques.com/

*/

public class correctOfficerGUI extends JFrame

{

private JPanel form;

private final JFrame f;

//public final int lineCount = 0;

//EASTERN NY

public static String nameInfoString= new String();

String facilities[] = {"blue","green", "yellow"};

public correctOfficerGUI()

{

//JFrame

f = new JFrame("Add Officer");

//int x = f.DoModal();

// Make a panel to hold the demo 揻orm", then

// add it to the top of the frame抯 content pane

//JPanel

form = new JPanel();

f.getContentPane().setLayout(new BorderLayout());

f.getContentPane().add(form, BorderLayout.NORTH);

// Set the form panel抯 layout to GridBagLayout

// and create a FormUtility to add things to it.

form.setLayout(new GridBagLayout());

JPanel spacerPanel = new JPanel();

spacerPanel.setLayout(new BorderLayout());

final JList list = new JList(facilities);

int index = 2;

list.setSelectedIndex( 1 );

list.setVisibleRowCount(1);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

//contentpane

form.add(new JScrollPane(list));

JButton addButton = new JButton("Add");

form.add(addButton);

//addButton.add(

addButton.addActionListener(

new ActionListener()

{

public void actionPerformed( ActionEvent actionEvent )//valueChanged(ListSelectionEvent e)

{

//f.DoModal();

System.out.println("********************************************");

JOptionPane.showMessageDialog(null, "The Officer has been Added.");

}

}

);

// Add an little padding around the form

form.setBorder(new EmptyBorder(2, 2, 2, 2));

f.setSize(300, 300);//230);

f.setVisible(true);

}

public static void main(String[] args)

{

correctOfficerGUI test = new correctOfficerGUI();

test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

Message was edited by:

poncho

ponchoa at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 7
So it's not really a JList problem at all. It's a JScrollPane problem. Hmmm. I don't know all that much about JScrollPane yet, but will learn from the API and hopefully camickr.
petes1234a at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 8

Consider using the JList method ensureIndexIsVisible(). I don't think it will do much before the list is actually visible.

Some other things...

There's a lot of stuff in there that obscures what's going on. If you're trying to see how to do something, remove things that are extraneous - a lot of the commented liines, the spacer panel, import statements etc.

Why does correctOfficerGUI extend JFrame and include a private JFrame member that is initialised, then shown? In your main method you set the default close operation of the test GUI - but this will have no effect as the test gui is never made visible! You might want to consider creating/showing/exiting the GUI along the lines exemplified by the HelloWorldSwing.java program in Sun's Tutorial. http://java.sun.com/docs/books/tutorial/uiswing/start/compile.html

pbrockway2a at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 9

I just did some reading... and they say that "a little knowledge is dangerous". Anyway, rather than using a JList, how about a class (it could extend JList) that implements the Scrollable interface? That way you can better control how the JScrollPane displays the data.

addendum: whoops! JList already DOES implement Scrollable!

Message was edited by:

petes1234

petes1234a at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 10

> whoops! JList already DOES implement Scrollable!

Indeed.

This is what I turned the code into in order to see how to make "Green" visible initially. (It's not intended to be "teh last thing in Swing", but hopefully it illustrates what I was getting at.)import java.awt.BorderLayout;

import java.awt.GridBagLayout;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

import javax.swing.Action;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JList;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.ListSelectionModel;

import javax.swing.SwingUtilities;

import javax.swing.border.EmptyBorder;

public class CorrectOfficerGUI extends JFrame {

private String facilities[] = {"blue", "green", "yellow"};

private JList list;

public CorrectOfficerGUI() {

super("Add Officer");

JPanel form = new JPanel(new GridBagLayout());

form.setBorder(new EmptyBorder(2, 2, 2, 2));

add(form, BorderLayout.NORTH);

list = new JList(facilities);

list.setVisibleRowCount(1);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

form.add(new JScrollPane(list));

JButton addButton = new JButton(addAct);

form.add(addButton);

}

/** Programmaticaly sets the selected item in the list. */

private void setSelected(int i) {

list.setSelectedIndex(i);

list.ensureIndexIsVisible(i);

}

private Action addAct = new AbstractAction("Add") {

/** Adds the officer currently selected in the list. */

public void actionPerformed(ActionEvent e) {

try {

// todo: add the officer here

System.out.printf("%s added%n", list.getSelectedValues()[0]);

} catch(ArrayIndexOutOfBoundsException aioobe) {

System.err.println("wtf? Nothing is selected!");

aioobe.printStackTrace();

return;

}

JOptionPane.showMessageDialog(null, "The Officer has been added.");

}

};

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

CorrectOfficerGUI test = new CorrectOfficerGUI();

test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

test.setSize(300, 300);

//test.pack();

test.setLocationRelativeTo(null);

test.setVisible(true);

test.setSelected(1);

}

});

}

}

I wonder if it should be a frame at all. It acts more like a JDialog.

pbrockway2a at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 11

Rather than make your JScrollPane anonymous, declare it and use it. You could then try something like this:

int index = 1; //index of item to highlight and display

list.setSelectedIndex(index);

list.setVisibleRowCount(1);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

JScrollPane listScrollPane = new JScrollPane(list);

form.add(listScrollPane);

int unitIncrement = list.getScrollableUnitIncrement(

listScrollPane.getViewport().getVisibleRect(), SwingConstants.VERTICAL, 1);

listScrollPane.getVerticalScrollBar().setUnitIncrement(unitIncrement);

listScrollPane.getVerticalScrollBar().setValue(unitIncrement * index);

*** Warning *** This is obtained by a first-time playing w/ API functions. I've never done this before and can't vouch for its stability in the long run. Good luck!

Message was edited by:

petes1234

petes1234a at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 12
to: pbrockwywhat are you trying to do in this code? It blows up when I try to run it...
ponchoa at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 13
> It blows up when I try to run it... Then read the error message and fix the problem. The error message tells you whats wrong.
camickra at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 14
Thank you petes1234, that worked. These are the line that did it:JScrollPane listScrollPane = new JScrollPane(list);form.add(listScrollPane);
ponchoa at 2007-7-12 22:22:19 > top of Java-index,Java Essentials,Java Programming...
# 15
Of course, If your list is SingleSelection, and you are only showing one item at a time, why would you not just use a combo box instead? Just one man's opinion.~Tim
SomeoneElsea at 2007-7-21 23:01:14 > top of Java-index,Java Essentials,Java Programming...
# 16
> to: pbrockwy> > what are you trying to do in this code? It blows up> when I try to run it...To the OP: Please take a close look at pbrockwy's program structure. It's a lot cleaner than yours. You would do well to emulate it.
petes1234a at 2007-7-21 23:01:14 > top of Java-index,Java Essentials,Java Programming...