Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8281197
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T09:56:54+00:00 2026-06-08T09:56:54+00:00

I’m trying to create a form with a JList and a button What I

  • 0

I’m trying to create a form with a JList and a button
What I want to do, is select an item from the JList, and then press the button to perform an action dependant on the selection. However, as soon as the button is clicked, the JList loses focus, and the selection disappears, making the button unable to determine what element was selected in the JList.

Is there a solution to this?
Thanks in advance 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T09:56:55+00:00Added an answer on June 8, 2026 at 9:56 am
    • I can’t see any issue with example from Oracle JList tutorial

    • have look at ListSelectionListener

    • maybe carefully with SelectionModes

    • can you please to describe whats is your goal

    code example

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class ListDemo extends JPanel implements ListSelectionListener {
    
        private JList list;
        private DefaultListModel listModel;
        private static final String hireString = "Hire";
        private static final String fireString = "Fire";
        private JButton fireButton;
        private JTextField employeeName;
    
        public ListDemo() {
            super(new BorderLayout());
            listModel = new DefaultListModel();
            listModel.addElement("Jane Doe");
            listModel.addElement("John Smith");
            listModel.addElement("Kathy Green");
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            list.setVisibleRowCount(5);
            JScrollPane listScrollPane = new JScrollPane(list);
            JButton hireButton = new JButton(hireString);
            HireListener hireListener = new HireListener(hireButton);
            hireButton.setActionCommand(hireString);
            hireButton.addActionListener(hireListener);
            hireButton.setEnabled(false);
            fireButton = new JButton(fireString);
            fireButton.setActionCommand(fireString);
            fireButton.addActionListener(new FireListener());
            employeeName = new JTextField(10);
            employeeName.addActionListener(hireListener);
            employeeName.getDocument().addDocumentListener(hireListener);
            String name = listModel.getElementAt(list.getSelectedIndex()).toString();
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
            buttonPane.add(fireButton);
            buttonPane.add(Box.createHorizontalStrut(5));
            buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
            buttonPane.add(Box.createHorizontalStrut(5));
            buttonPane.add(employeeName);
            buttonPane.add(hireButton);
            buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            add(listScrollPane, BorderLayout.CENTER);
            add(buttonPane, BorderLayout.PAGE_END);
        }
    
        class FireListener implements ActionListener {
    
            public void actionPerformed(ActionEvent e) {
                int index = list.getSelectedIndex();
                listModel.remove(index);
                int size = listModel.getSize();
                if (size == 0) { //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else { //Select an index.
                    if (index == listModel.getSize()) {
                        index--;
                    }
                    list.setSelectedIndex(index);
                    list.ensureIndexIsVisible(index);
                }
            }
        }
    
        class HireListener implements ActionListener, DocumentListener {
    
            private boolean alreadyEnabled = false;
            private JButton button;
    
            public HireListener(JButton button) {
                this.button = button;
            }
    
            public void actionPerformed(ActionEvent e) {
                String name = employeeName.getText();
                if (name.equals("") || alreadyInList(name)) {
                    Toolkit.getDefaultToolkit().beep();
                    employeeName.requestFocusInWindow();
                    employeeName.selectAll();
                    return;
                }
                int index = list.getSelectedIndex(); //get selected index
                if (index == -1) { //no selection, so insert at beginning
                    index = 0;
                } else {           //add after the selected item
                    index++;
                }
                listModel.insertElementAt(employeeName.getText(), index);
                //listModel.addElement(employeeName.getText());
                employeeName.requestFocusInWindow();
                employeeName.setText("");
                list.setSelectedIndex(index);
                list.ensureIndexIsVisible(index);
            }
    
            protected boolean alreadyInList(String name) {
                return listModel.contains(name);
            }
    
            public void insertUpdate(DocumentEvent e) {
                enableButton();
            }
    
            public void removeUpdate(DocumentEvent e) {
                handleEmptyTextField(e);
            }
    
            public void changedUpdate(DocumentEvent e) {
                if (!handleEmptyTextField(e)) {
                    enableButton();
                }
            }
    
            private void enableButton() {
                if (!alreadyEnabled) {
                    button.setEnabled(true);
                }
            }
    
            private boolean handleEmptyTextField(DocumentEvent e) {
                if (e.getDocument().getLength() <= 0) {
                    button.setEnabled(false);
                    alreadyEnabled = false;
                    return true;
                }
                return false;
            }
        }
    
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
    
                if (list.getSelectedIndex() == -1) {
                    fireButton.setEnabled(false);
                } else {
                    fireButton.setEnabled(true);
                }
            }
        }
    
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("ListDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new ListDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
I'm trying to select an H1 element which is the second-child in its group
I have a text area in my form which accepts all possible characters from
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.