Using a JList

Hi everyone! Happy new year.
Okay, I have some work for some keen programmer out there to do. There are 10 duke dollars avaliable to whoever can help me with this problem.
I am using a JList to display a list of milestones which are required later on in my project. When no item is selected from the list, I want the 'Delete Milestone' button to automatically disable and when an item is selected from the list, I want it to auto enable. If the list is empty, then the button should remain disabled. For this to work I think I need some sort of ListSelectionListener but I am not sure how to do this. At the moment I get an exception whenever I click on the 'Delete Milestone' button and no selection has been made, which is understandable.
Another thing that I need doing is that if a milestone is added to the list, and the 'Critical Milestone' is selected, then whenever that item is selected from the list, the background colour should be red; whenever a 'Non-critical Milestone' is created, then that should remain with a yellow background whenever selected from the list. At the moment, the background colour changes to whatever the last added milestone happened to be - either red or yellow for all entries that have been added to the list. If anyone can help me with this then that would be really appreciated and very helpful. The 4 files can be found below - just run the 'AddMilestoneTest' class to start the app. Thanks.
* AddMilestoneTest.java
* 29/12/02 (Date start)
* This class is for iteration purposes for
* the "Add Milestone" wizard
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AddMilestoneTest extends JPanel
private JButton addMilestoneButton;
public JFrame addMilestoneFrame;
static AddMilestoneTest instance;     
public AddMilestoneTest()
     instance = this;
// create new button
addMilestoneButton = new JButton("Add Milestone");
// create tooltip for every button
addMilestoneButton.setToolTipText("Add Milestone");
// add our button to the JPanel
add(addMilestoneButton);
// construct button action
AddMilestoneListener listener1 = new AddMilestoneListener();
// Add action listener to button
addMilestoneButton.addActionListener(listener1);
private class AddMilestoneListener implements ActionListener
public void actionPerformed(ActionEvent evt)
addMilestoneFrame = new JFrame("Add Milestone Wizard*");
MilestoneSplitPanel milestoneSplitPanel = new MilestoneSplitPanel();
addMilestoneFrame.getContentPane().add(milestoneSplitPanel);
addMilestoneFrame.setSize(850, 305);
addMilestoneFrame.setVisible(true);
// Main entry point into the program
public static void main(String[] args)
// Create a frame to hold us and set its title
JFrame frame = new JFrame("Add Milestone Iteration");
// Set frame to close after user request
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add our panel to the frame
AddMilestoneTest amt = new AddMilestoneTest();
frame.getContentPane().add(amt, BorderLayout.CENTER);
// Resize the frame
frame.setSize(680, 480);
// Make the windows visible
frame.setVisible(true);
* MilestoneSplitPanel.java
* 29/12/02
* This class creates a split between the
* AddMilestonePanel and the CurrentMilestonePanel
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class MilestoneSplitPanel extends JPanel
// Declare a split panel
JSplitPane splitPanel;
// Declare the panels required here
AddMilestonePanel addMilestonePanel;
CurrentMilestonePanel currentMilestonePanel;
public MilestoneSplitPanel()
// Create the panels required
addMilestonePanel = new AddMilestonePanel();
currentMilestonePanel = new CurrentMilestonePanel();
// Create the split panel with our two panels
splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, currentMilestonePanel, addMilestonePanel);
splitPanel.setDividerLocation(200);
//Provide minimum sizes for the two components in the split pane
addMilestonePanel.setMinimumSize(new Dimension(350, 200));
currentMilestonePanel.setMinimumSize(new Dimension(100, 100));
//Add the split panel to this panel.
add(splitPanel, BorderLayout.CENTER);
* AddMilestonePanel.java
* 29/12/02 (Date start)
* This class is for iteration purposes for
* the "Add Milestone" wizard
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class AddMilestonePanel extends JPanel
private JLabel milestoneNameLabel;
private JLabel milestoneNameMaxChar;
private JLabel milestoneECDLabel;
private JLabel forwardSlash1;
private JLabel forwardSlash2;
private JLabel dateFormatLabel;
private JLabel selectOne;
private JTextField milestoneName;
private JComboBox theDate;
private JComboBox theMonth;
private JComboBox theYear;
private ButtonGroup group;
private JRadioButton criticalMilestone;
private JRadioButton nonCriticalMilestone;
private JButton addMilestone;
private JButton deleteMilestone;
private JButton cancel;
private JButton finish;
private JList currentMilestones;
static AddMilestonePanel instance;
public String dateSelected;
public String monthSelected;
public String yearSelected;
public AddMilestonePanel()
instance = this;
// create additional panels to hold objects
JPanel topPanel = new JPanel();
JPanel middlePanel = new JPanel();
JPanel lowerPanel = new JPanel();
JPanel buttonPanel = new JPanel();
// Create a border around the "toppanel"
Border etched = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
Border titled = BorderFactory.createTitledBorder(etched, "Provide a name for the milestone");
topPanel.setBorder(titled);
// Create a border around the "middlepanel"
Border etched1 = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
Border titled1 = BorderFactory.createTitledBorder(etched1, "Enter an estimated completion date of the milestone");
middlePanel.setBorder(titled1);
// Create a border around the "lowerpanel"
Border etched2 = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.blue);
Border titled2 = BorderFactory.createTitledBorder(etched2, "Choose whether the milestone is critical or non-critical");
lowerPanel.setBorder(titled2);
// initialise JLabel objects
milestoneNameLabel = new JLabel("Milestone Name: ");
milestoneNameMaxChar = new JLabel("(Max 20 chars)");
milestoneECDLabel = new JLabel("Estimated Completion Date: ");
forwardSlash1 = new JLabel("/");
forwardSlash2 = new JLabel("/");
dateFormatLabel = new JLabel("(Date/Month/Year)");
selectOne = new JLabel("(Select One)");
// create textfield for the milestone name
milestoneName = new JTextField(20);
milestoneName.setColumns(15);
topPanel.validate();
// create the combo boxes for the date
theDate = new JComboBox(new String[]
"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16",
"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
theDate.setEditable(false);
theMonth = new JComboBox(new String[]
"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"
theMonth.setEditable(false);
theYear = new JComboBox(new String[]
"2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012"
theYear.setEditable(false);
// create the radio buttons and add them to the group
group = new ButtonGroup();
criticalMilestone = new JRadioButton("Critical Milestone", true);
nonCriticalMilestone = new JRadioButton("Non-critical Milestone", false);
group.add(criticalMilestone);
group.add(nonCriticalMilestone);
// create the buttons
addMilestone = new JButton("Add Milestone", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/addMilestoneIcon.JPG"));
deleteMilestone = new JButton("Delete Milestone", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/deleteMilestone.JPG"));
cancel = new JButton("Cancel", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/StopControl.gif"));
finish = new JButton("Finish", new ImageIcon("D:/My Uni Work/Final Year Project/Graphics/bluearrow.gif"));
// set tooltips for buttons
addMilestone.setToolTipText("Add Milestone");
deleteMilestone.setToolTipText("Delete Milestone");
cancel.setToolTipText("Cancel");
finish.setToolTipText("Finish");
// set the state of the buttons when first run
deleteMilestone.setEnabled(false);
finish.setEnabled(false);
// add objects to panels
topPanel.add(milestoneNameLabel);
topPanel.add(milestoneName);
topPanel.add(milestoneNameMaxChar);
middlePanel.add(milestoneECDLabel);
middlePanel.add(theDate);
middlePanel.add(forwardSlash1);
middlePanel.add(theMonth);
middlePanel.add(forwardSlash2);
middlePanel.add(theYear);
middlePanel.add(dateFormatLabel);
lowerPanel.add(criticalMilestone);
lowerPanel.add(nonCriticalMilestone);
lowerPanel.add(selectOne);
buttonPanel.add(addMilestone);
buttonPanel.add(deleteMilestone);
buttonPanel.add(cancel);
buttonPanel.add(finish);
// use Box layout to arrange panels
Box hbox1 = Box.createHorizontalBox();
hbox1.add(topPanel);
Box hbox2 = Box.createHorizontalBox();
hbox2.add(middlePanel);
Box hbox3 = Box.createHorizontalBox();
hbox3.add(lowerPanel);
Box hbox4 = Box.createHorizontalBox();
hbox4.add(buttonPanel);
Box vbox = Box.createVerticalBox();
vbox.add(hbox1);
vbox.add(Box.createGlue());
vbox.add(hbox2);
vbox.add(Box.createGlue());
vbox.add(hbox3);
vbox.add(Box.createGlue());
vbox.add(hbox4);
this.add(vbox, BorderLayout.NORTH);
// create instance of cancelButtonListener
CancelButtonListener cancelListen = new CancelButtonListener();
// create instance of AddMilestoneListener
AddMilestoneListener milestoneListener = new AddMilestoneListener();
// create instance of DeleteMilestoneListener
DeleteMilestoneListener deleteListener = new DeleteMilestoneListener();
// add actionListener for the buttons
cancel.addActionListener(cancelListen);
addMilestone.addActionListener(milestoneListener);
deleteMilestone.addActionListener(deleteListener);
private class CancelButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if(source == cancel)
AddMilestoneTest.instance.addMilestoneFrame.setVisible(false);
private class AddMilestoneListener implements ActionListener
public void actionPerformed(ActionEvent event)
String milestoneNameText = milestoneName.getText().trim();
int textSize = milestoneNameText.length();
dateSelected = (String)theDate.getSelectedItem();
monthSelected = (String)theMonth.getSelectedItem();
yearSelected = (String)theYear.getSelectedItem();
if(textSize > 20)
//display a JOptionPane
JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have entered a title that is greater than 20 characters.",
"Text too Long", JOptionPane.ERROR_MESSAGE);
else if(textSize == 0)
//display a JOptionPane
JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have not entered a milestone name. Please do so (Maximum 20 Characters).",
"No Project Name Entered", JOptionPane.ERROR_MESSAGE);
else if(dateSelected == "30" && monthSelected == "02" || dateSelected == "31" && monthSelected == "02" || dateSelected == "31" && monthSelected == "04" ||
dateSelected == "31" && monthSelected == "06" || dateSelected == "31" && monthSelected == "09" || dateSelected == "31" && monthSelected == "11")
JOptionPane.showMessageDialog(AddMilestonePanel.instance, "You have selected an invalid date. Re-check that the date is valid.",
"Invalid Date Selected", JOptionPane.ERROR_MESSAGE);
} // ANOTHER CHECK IS REQUIRED HERE WHEN INTEGRATING - IF DATE ENETERED IS WITHIN THE START DATE AND END DATE OF THE PROJECT
else
deleteMilestone.setEnabled(true);
finish.setEnabled(true);
if(criticalMilestone.isSelected())
CurrentMilestonePanel.instance.listModel.addElement(milestoneNameText);
CurrentMilestonePanel.instance.currentMilestoneList.setSelectionBackground(Color.red);
else if(nonCriticalMilestone.isSelected())
CurrentMilestonePanel.instance.listModel.addElement(milestoneNameText);
CurrentMilestonePanel.instance.currentMilestoneList.setSelectionBackground(Color.yellow);
private class DeleteMilestoneListener implements ActionListener
public void actionPerformed(ActionEvent event)
if(CurrentMilestonePanel.instance.listModel.size() > 0)
int selectedItemIndex = CurrentMilestonePanel.instance.currentMilestoneList.getSelectedIndex();
CurrentMilestonePanel.instance.listModel.remove(selectedItemIndex);
* CurrentMilestonePanel.java
* 29/12/02 (Date start)
* This class is for iteration purposes for
* the "Add Milestone" wizard
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class CurrentMilestonePanel extends JPanel
public JList currentMilestoneList;
private JLabel currentMilestonesAdded;
// List Model that will hold the data for the list
public DefaultListModel listModel;
// Scroll pane that will contain the list
private JScrollPane scrollPaneList;
static CurrentMilestonePanel instance;
// Constructor
public CurrentMilestonePanel()
instance = this;
// create label
currentMilestonesAdded = new JLabel("Current Milestones Added");
listModel = new DefaultListModel();
//listModel.addElement("No Milestones Added");
// Create the list
currentMilestoneList = new JList(listModel);
// Set single selection, and select the first item
currentMilestoneList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
currentMilestoneList.setSelectedIndex(0);
// Create a scroll panel to hold list
scrollPaneList = new JScrollPane(currentMilestoneList);
// Set the preferred size
scrollPaneList.setPreferredSize(new Dimension(130, 200));
//Add the scroll pane to this panel.
add(currentMilestonesAdded, BorderLayout.NORTH);
add(scrollPaneList, BorderLayout.CENTER);

I suggest that you look into the swing tutorial. There are some samples of how to write ListSelectionListener.
I quickly scanned your code for the DeleteMilestoneListener. You get an exception here because you don't check if an item is selected in the list.

Similar Messages

  • Scroll bar in JPopupMenu when used in JList

    Hi,
    I want variable list (not combo box) where I can add multiple JMenuItems through JPopupMenu. I have created JList in JScrollPane and I have added multiple JMenuItems one by one but in output I am getting the list of JMenuItems without scrollbar. There is no way I can navigate to last JMenuItem in the JList. Could someone help me with integration of JList, JMenuItems, JPopupMenu with scroll bars?
    Below given is the sample code. GUI components have been added through Netbeans.
    public void updatePopUp()
    final JPopupMenu menu = new JPopupMenu();
    menu.setBorder(null);
    menu.setAutoscrolls(true);
    JMenuItem item = new JMenuItem("JMenuItem");
    item.addActionListener(this);
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    item = new JMenuItem("JMenuItem");
    menu.add(item);
    menu.setVisible(true);
    menu.pack();
    varList.add(menu);
    // Set the component to show the popup menu
    /* this.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    public void mouseReleased(MouseEvent evt) {
    if (evt.isPopupTrigger()) {
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
    }

    I was going to say try setting the preferred (or maximum) size of the scrollpane to force it to be no larger than you want.
    But ...
    a) I don't see you putting menu items in a JList in that code. You are putting them directly into the popup menu (aka, the normal way to do things).
    b) Calling setAutoscrolls() on the JPopupMenu does not make it a "scrollable" menu. It is for supporting dragging of components in a scrollpane (usually). Read the API docs.

  • JTable used as a JList

    I am using a JTable as a JList (because it displays two columns). Above the JTable is an entry field when the user selects an item in the list with the mouse it adds it the entry field, I use a ListSelectionlistener This is fine.
    I then tested it using the keyboard. As I scroll down the list with the up/down cursor keys it adds each entry to the entry field. This is not what I was expecting I thought you would be able to scroll down the list and then press Enter/Space to select the record and add it to the list.
    I could add a button that the user has to select after selecting from the list before it is added to the entry field, but that creates an extra uneccessary stepo for mouse users. And one of my design goals for this project was to minimize the number of steps needed to complete any task.
    Does anybody know how to do what i want, or its it a bad idea ?

    Tables don't support the concept of an ActionEvent when you press the enter key. You could use a JList with a custom renderer to display two columns:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ListMultiColumn extends JFrame
         public ListMultiColumn()
              String[] tabs =
                   "123456\tone",
                   "2\ta really really long description goes here",
                   "3\tthree",
                   "41\tfour"
              JList list = new JList( tabs );
    //          list.setCellRenderer( new TextAreaRenderer() );
              list.setCellRenderer( new TextPaneRenderer() );
              list.setSelectedIndex(2);
              getContentPane().add( list );
         public static void main(String[] args)
              JFrame frame = new ListMultiColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible( true );
         **  Tabs are easier to use in a JTextArea, but not very flexible
         class TextAreaRenderer extends JTextArea implements ListCellRenderer
              public TextAreaRenderer()
                   setBackground(Color.blue);
                   setTabSize(10);
              public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus)
                   System.out.println(getBackground());
                   setText(value.toString());
                   setBackground(isSelected ? list.getSelectionBackground() : null);
                   setForeground(isSelected ? list.getSelectionForeground() : null);
                   return this;
         **  Tabs are harder to use in a JTextPane, but much more flexible
         class TextPaneRenderer extends JTextPane implements ListCellRenderer
              private final int TAB_COLUMN = 10;
              public TextPaneRenderer()
                   setMargin( new Insets(0, 0, 0, 0) );
                   FontMetrics fm = getFontMetrics( getFont() );
                   int width = fm.charWidth( 'w' ) * TAB_COLUMN;
                   TabStop[] tabs = new TabStop[1];
                   tabs[0] = new TabStop( width, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE );
                   TabSet tabSet = new TabSet(tabs);
                   SimpleAttributeSet attributes = new SimpleAttributeSet();
                   StyleConstants.setTabSet(attributes, tabSet);
                   getStyledDocument().setParagraphAttributes(0, 0, attributes, false);
              public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus)
                   setText( value.toString() );
                   setBackground(isSelected ? list.getSelectionBackground() : null);
                   setForeground(isSelected ? list.getSelectionForeground() : null);
                   return this;
    }

  • Removing Data from a Database using JList

    Hi,
    I have the following JList with a "Remove" button.
    I have managed to populate the JList with entries from the DataBase but now i am having problems removing the data from the data base using the JList.
    What i am trying to achieve is, when an entry is selected from the JList and the "Remove" button is hit, the entry should be removed from the JList and from the database.
    How do i do this, please help..
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.*;
    public class RemoveD extends JDialog {
        private JList list;
        private JButton removeButton;
        private JScrollPane scrollPane;
        private Connection conn = null;
        private Statement stat = null;
        private ResultSet rs = null;
        String names = new String();
        private DefaultListModel listModel = new DefaultListModel();
        public RemoveD(Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        private void initComponents() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            try {
                String userID = "";
                String psw = "";
                String url;
                url = "jdbc:mysql://localhost:3306/mqnames";
                conn = DriverManager.getConnection(url, userID, psw);
                stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                rs = stat.executeQuery("SELECT queueName FROM queuenametable");
                int j = 0;
                while (rs.next()) {
                    names = rs.getString(1);
                    System.out.println("rs: " + names);
                    listModel.addElement(names);
                }//end of While
                stat.close();
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            scrollPane = new JScrollPane();
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            removeButton = new JButton();
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().setLayout(new GridLayout(2, 0));
            scrollPane.setViewportView(list);
            getContentPane().add(scrollPane);
            removeButton.setText("Remove");
            removeButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    removeButtonActionPerformed(evt);
            getContentPane().add(removeButton);
            pack();
        private void removeButtonActionPerformed(ActionEvent evt) {
        public static void main(String args[]) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    RemoveD dialog = new RemoveD(new JFrame(), true);
                    dialog.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                            System.exit(0);
                    dialog.setVisible(true);
    }

    Ask a specific question. Do you know how to get the selected item in the list? Do you know how to write a delete query in SQL?

  • Selection problem in a JList !!!!

    I am using a JList and on the selection of an item in this JList - I enable and disable some buttons.
    I have currenlty added a ListSelectionListener that allows me to trap the valuechanged event and thus if any item in the list is selected / deselected, i can enable/ disable the buttons.
    Now the abuv works fine with click and Ctrl clicking (to deselect),
    However if i come into the JList from another control (a JCombo) by tabbing and then use the arrow keys once the control is in the JList, the up and down arrow keys allow me to change the selection in the list.
    But, the valueChanged event does not come in the above case and hence the buttons do not enable/disable !!!
    Can you tell me what can be the problem?????

    Add a key listener and handle the KeyEvent
    Sachin

  • Can JTable cell acts as JList?

    I was planning to create an Event Calendar view in Monthly. Currently my jTable cell extends JTextArea. My problem is that, for example, today I got 2 events display in one cell, when a user double-click the "today" cell, an edit form will pop out, if there are 2 events in one cell, how I know which events to be edit? In this case I was thinking to use JList instaed of jTextArea. so i can choose which event to be edit. Is there any example showing how to implement jTable with jList cell? or is there any other method to overcome it?

    I haven't used a JList in a JTable so far, but for a JComboBox you find a working example in the tutorial. That may give you some ideas.
    What I did use is a (read only) JTable in a JTable. So if you don't achieve your goal with JList there are alternatives.
    But wait for our table specialists to come along.

  • Huge combo boxes in JFileChooser/JList text truncated in 1.4.0

    Hi there,
    We have an application which works fine on Sun JRE 1.3.1
    Recently we started supporting Sun JRE 1.4.0
    But we have some problems with GUI in Sun JRE 1.4.0
    In the JFileChooser dialog the combo box for Folder name
    and file filter is atleast twice as big as normal in when
    using JRE 1.4.0. This seems to be happening only in some particular
    machines. And if we run the application using JRE 1.3.1, on the machine which has problems with JRE 1.4.0, everything works fine.
    Also we use a JList with a custom cell rendered in the application.
    the cell renderer returns a JLabel component with "monospaced" font set in it. In some machines (same machines which has the JFileChooser problem) the upper half of each item in the JList is truncated. This also works fine is we use JRE 1.3.1 on the same machine.
    Please help me if you have any info on these issues.
    Any pointers to related issues on this forum or bug database is highly appreciated.
    Thanks in adance

    Hehe. Give it more time. Could you explain more about what you mean?
    You have a form with the select combo box in it. The user chooses a value from the combo box. Then submits the form. You want to put the value of the option inside the sql statement right? Not the words displayed by the option, but the item you put in the value section right?
    If so, its rather easy:
    query = "INSERT INTO Table VALUE( comboType, \""+request.getParameter( "text")+"\"); The \" might not be necessary depending on how the value is stored.

  • Problems with JList

    Hi all,
    I'm trying to use a JList for a program that I'm making.
    To initialize the JList, I use the following code:
    public static JList menu;
    public MadLibsManagerGui() {
    menu = new JList(MadLibsGui.getComboInfo());
    the getComboInfo() method returns an array of strings. This should work, no? But, it doesn't seem to be working! When i try printing the number of indices in the jlist, i get -1even though all of my strings (from the array) do get displayed in the JList. Any ideas? Thanks so much! any help is greatly appreciated.
    PS. Does anyone know how to close a JFrame using the push of a button?

    Even when i pass it an integer constant, i get the
    exceptionA couple of things:
    First of all, the remove(int) method defined in JList is inherited from java.awt.Container: it is used for removing a child Component with the given index from a Container. In other words, you cannot use it to remove items from the list.
    In fact, there are no methods defined in the JList API for adding or removing items once the list is created. This is because the ListModel interface that defines the data that backs the JList is immutable.
    It is still possible, of course, to add and remove items from a JList. The trick is to use a custom ListModel implementation, such as DefaultListModel, that allows such modifications. See the JList tutorial for examples of this.
    Secondly, if something is selected in the list, getSelectedIndex() will not return -1. If the JList you see on your screen has something selected, but getSelectedIndex() returns -1 when called on a JList reference in your code, then chances are good that you have two different JList objects. The JList that you add to the UI is not the same JList instance you refer to when calling getSelectedIndex().

  • Reorder items in JTree using drag-and-drop

    Title says it all: before I start re-inventing the wheel, any code out there?
    Think of the code that I need as an outliner.

    Did you ever find a solution to this. I'm looking to implement a similar interface using a JList where the user can reorder drawing layers by dragging and dropping.
    I'm temped to use a scrollpane and roll my own drag reorder code, so any supported behaviors would be welcome.
    thanks,
    Steven

  • Changing JList cell renderer on selection

    Hi,
    In our application we need to change the renderer of the selected cell of JList to JTextArea while maintaining default cell renderer for unselected cells. I tried by providing custom cell renderer (code is given below) but it does not work..:-(. Though the component used by JList for rendering the cell is JTextArea, the height of the cell remains same as that of unselected cells. Our requirement is to change the cell height of the selected row so as to give a feel that selected row expands and shows some more information about the selected item to the user.
    Here is the code snippet of the cell renderer that I wrote:
    class CellRenderer1 extends DefaultListCellRenderer{
    private JTextArea selTxtArea;
    CellRenderer1() {
    selTxtArea = new JTextArea(3,20);
    this.setOpaque(true);
    public Component getListCellRendererComponent(JList list,
    Object value, int index,
    boolean isSelected, boolean cellHasFocus) {
    String name = (String) value;
    if ( isSelected ) {
    selTxtArea.setBackground(list.getSelectionBackground());
    selTxtArea.setForeground(list.getSelectionForeground());
    selTxtArea.setText(name + "\n" + name);
    return selTxtArea;
    else {
    this.setBackground(list.getBackground());
    this.setForeground(list.getForeground());
    this.setText(name);
    return this;
    //return this;
    Any pointers or help will be highly appreciated.
    Thanks
    Atul

    JList calculates fixedCellHeight and then uses the same for every cell. This was causing the problem. By overriding the getRowHeight method of BasicListUI class I was able to achieve different cell heights for selected and unselected rows. Following is the code snippet which shows how this was achieved:
    protected int getRowHeight(int row) {
    if ( (cellHeights == null) || (cellHeights.length < row )) {
    cellHeights = new int[row];
    ListModel model = list.getModel();
    Object value = model.getElementAt(row);
    ListSelectionModel selModel = list.getSelectionModel();
    boolean isSelected = selModel.isSelectedIndex(row);
    Component comp = list.getCellRenderer().
    getListCellRendererComponent( list, value, row,
    isSelected, false);
    Dimension dim = comp.getPreferredSize();
    int height = dim.height;
    cellHeights[row] = height;
    return cellHeights[row];
    }

  • Jlist as a Cell Renderer

    Hi ,
    I would reaally appreciate if someone could post an example of using a JList as a custom Cell renderer
    Thank you.

    Here's a start (I couldn't be bothered to set an editor too):import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test extends JFrame {
        public Test () {
            JTable table = new JTable (new TestTableModel ());
            table.setDefaultRenderer (Integer[].class, new TestTableCellRenderer ());
            table.setRowHeight (50);
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (new JScrollPane (table));
            setDefaultCloseOperation (DISPOSE_ON_CLOSE);
            setTitle ("Test");
            pack ();
            setLocationRelativeTo (null);
            setVisible (true);
        public static void main (String[] parameters) {
            new Test ();
        private class TestTableModel implements TableModel {
            private final static int N = 10;
            private Object[][] data;
            private ColumnData[] columnData;
            public TestTableModel () {
                data = new Object[N][2];
                for (int i = 0; i < N; i ++) {
                    data[0] = new Integer (i);
    data[i][1] = new Integer[i + 1];
    for (int j = 0; j <= i; j ++) {
    ((Integer[]) data[i][1])[j] = new Integer (j);
    columnData = new ColumnData[] {
    new ColumnData ("n", Integer.class),
    new ColumnData ("0..n", Integer[].class)
    public int getColumnCount () {
    return columnData.length;
    public int getRowCount () {
    return data.length;
    public boolean isCellEditable (int row, int column) {
    return false;
    public void setValueAt (Object value, int row, int column) {}
    public Class getColumnClass (int column) {
    return columnData[column].classType;
    public Object getValueAt (int row, int column) {
    return data[row][column];
    public String getColumnName (int column) {
    return columnData[column].name;
    public void addTableModelListener (TableModelListener listener) {}
    public void removeTableModelListener(TableModelListener listener) {}
    private class ColumnData {
    public String name;
    public Class classType;
    public ColumnData (String name, Class classType) {
    this.name = name;
    this.classType = classType;
    private class TestTableCellRenderer extends JScrollPane implements TableCellRenderer {
    private JList list;
    public TestTableCellRenderer () {
    list = new JList ();
    setViewportView (list);
    public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column) {
    list.setListData ((Integer[]) value);
    return this;
    Kind regards,
      Levi

  • Strange repaint behaviour with JList & Keyboard actions

    Hi everyone,
    This is my first post to the forum. You guys have been a great help in the past and I hope to contribute more in the future.
    Anyways, I've encountered some strange repainting behaviour with a JDialog that uses a JList and a JButton. The dialog is fairly straight-forward and basically this is how it works (like an open file dialog - yes I'm implementing my own filechooser of sorts):
    * JList lists a number of simple items that the user can select from.
    * Once a selection is made, an Open button (JButton) is enabled.
    * <ENTER> key is registered (using registerKeyboardAction()) with a JPanel which is used as the main content pane in the dialog.
    * The user can either click on the Open Button or hit the <ENTER> key which then closes the dialog and runs whatever logic that needs to.
    Now, the repaint problem comes in when:
    1. User selects an item.
    2. User hits the <ENTER> button
    3. Dialog closes
    4. User brings the dialog back up. This entails reloading the list by removing all elements from the list and adding new ones back in.
    5. Now... if the user uses the mouse to select an item lower in the list than what was done in step #1, the selection is made, but the JList doesn't repaint to show that the new selection was made.
    I didn't include a code sample because the dialog setup is totally straight-forward and I'm not doing anything trick (I've been doing this kind of thing for years now).
    If I remove the key registration for the <ENTER> key from the dialog, this problem NEVER happens. Has anyone seen anything like this? It's a minor problem since my workaround is to use a ListSelectionListener which manually calls repaint() on the JList inside the valueChanged() method.
    Just curious,
    Huy

    Oh, my bad. I'm actually using a JToggleButton and not a JButton, so the getRootPane().setDefaultButton() doesn't apply because it only takes JButton as an input param. I wonder why it wasn't implemented to take AbstractButton. hmmm.

  • Selection in a combo when using Usebean??

              Hi All,
              In the JSP page, to select/display employeeType (Consulatant/Administrative Employee), i am having a combo box. I am using a UseBean tag and employeeType variable of the used bean, will have one of these values. How to show the selected employeeType?
              One way to acheive could be using "OPTION SELECTED TAG". Is there any better way to achieve this?
              Thanks,
              Amar
              

    Use a JList for multiple selection.

  • Do I use JFrame or JDialog?

    Hi,
    I wanted to create a dialog which allows me to have two JTextArea's. In one list I list possible selection for the user. In the other text area, all the files the user selected will be in the text area. There will be two buttons for removal/addition of these items from the second text area. When you hit the OK button the owner of the dialog needs to grab that info.
    Can an extension of a JDialog do this? Would it be suited for this? Or should I use an extension of a JFrame?
    thanks for any help in advance,
    Geoff

    I would use a JList. The Swing tutorial on "How to Use Lists" gives an example of how to add/remove items from a single list. Changing this to work with two lists should be easy:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#mutable

  • JList problems, can't write to a list

    Hi there....can anyone help???
    I'm having a problem with a dialog box...I use a dialog box to logon a new user (client) to my server, but the GUI on the client's side isn't showing who's online so to speak(I'm using a JList as my 'buddy' list type of window)....How do I get the dialog box to send the user's name to my client's GUI and add it to my who's online box??? Conversely how do I get the name to be removed when the user disconnects from the server??? Thanks everyone for any help you can provide....

    You need to refresh the JList every time the data changes:
    JList myjlist = new JList();
    Vector data = new Vector(); //or use an array of type Object
    //data changes
    myjlist.setListData(data);

Maybe you are looking for

  • Tricky problem: TM makes only one backup and then can't find disk anymore

    I had a problem with TM backups and erased the whole TC, because that solved a problem I had in the past. My iMac is connected via Ethernet. My notebooks via WLAN. BUT THIS PROBLEM OCCURS ON MY IMAC ONLY. Then: 1) I defined new accounts. 2) Next back

  • Video to Multiple ATV2's

    Just a quick question for all of the Apple TV guru's out there, and, if this has been covered already, i apologize. i did search but found nothing of what i was asking I have 3 apple TV's in my house. Can I push a video to all 3 apple TV's at the sam

  • Clarification Needed For Alerts : UDF

    Hi Team, I am configuaring AE & IE Alerts . In IE Alerts, In Container variables am seeing UDF ALERT XX, etc.. Im unable to understand what is the use of UDF ALERTs in Container variables????? Thanks in Advance.

  • Problem with Windows Data Execution Prevention

    Hi. I'm running Safari 5.1.2 on Windows Vista Business. Whenever I try to print a web page (any page) Windows reports a Data Execution Prevention and closes Safari. I can always print the same web page from IE, and I can always print to PDF. How do I

  • Main method errors

    I am trying to create the Euclid Algorithm in a simple command line application. I get the following error when I try to compile... Cannot make a static reference to the non-static method getInputs() Cannot make a static reference to the non-static m