Advertisement
fabioceep

JAVA: Exemplo de JList

Feb 23rd, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.99 KB | None | 0 0
  1. /*
  2.  * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  *   - Redistributions of source code must retain the above copyright
  9.  *     notice, this list of conditions and the following disclaimer.
  10.  *
  11.  *   - Redistributions in binary form must reproduce the above copyright
  12.  *     notice, this list of conditions and the following disclaimer in the
  13.  *     documentation and/or other materials provided with the distribution.
  14.  *
  15.  *   - Neither the name of Oracle or the names of its
  16.  *     contributors may be used to endorse or promote products derived
  17.  *     from this software without specific prior written permission.
  18.  *
  19.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20.  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21.  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30.  */
  31.  
  32. package listdemo;
  33.  
  34. import java.awt.*;
  35. import java.awt.event.*;
  36. import javax.swing.*;
  37. import javax.swing.event.*;
  38.  
  39. /* ListDemo.java requires no other files. */
  40. public class ListDemo extends JPanel
  41.                       implements ListSelectionListener {
  42.     private JList list;
  43.     private DefaultListModel listModel;
  44.  
  45.     private static final String hireString = "Hire";
  46.     private static final String fireString = "Fire";
  47.     private JButton fireButton;
  48.     private JTextField employeeName;
  49.  
  50.     public ListDemo() {
  51.         super(new BorderLayout());
  52.  
  53.         listModel = new DefaultListModel();
  54.         listModel.addElement("Jane Doe");
  55.         listModel.addElement("John Smith");
  56.         listModel.addElement("Kathy Green");
  57.  
  58.         //Create the list and put it in a scroll pane.
  59.         list = new JList(listModel);
  60.         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  61.         list.setSelectedIndex(0);
  62.         list.addListSelectionListener(this);
  63.         list.setVisibleRowCount(5);
  64.         JScrollPane listScrollPane = new JScrollPane(list);
  65.  
  66.         JButton hireButton = new JButton(hireString);
  67.         HireListener hireListener = new HireListener(hireButton);
  68.         hireButton.setActionCommand(hireString);
  69.         hireButton.addActionListener(hireListener);
  70.         hireButton.setEnabled(false);
  71.  
  72.         fireButton = new JButton(fireString);
  73.         fireButton.setActionCommand(fireString);
  74.         fireButton.addActionListener(new FireListener());
  75.  
  76.         employeeName = new JTextField(10);
  77.         employeeName.addActionListener(hireListener);
  78.         employeeName.getDocument().addDocumentListener(hireListener);
  79.         String name = listModel.getElementAt(
  80.                               list.getSelectedIndex()).toString();
  81.  
  82.         //Create a panel that uses BoxLayout.
  83.         JPanel buttonPane = new JPanel();
  84.         buttonPane.setLayout(new BoxLayout(buttonPane,
  85.                                            BoxLayout.LINE_AXIS));
  86.         buttonPane.add(fireButton);
  87.         buttonPane.add(Box.createHorizontalStrut(5));
  88.         buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
  89.         buttonPane.add(Box.createHorizontalStrut(5));
  90.         buttonPane.add(employeeName);
  91.         buttonPane.add(hireButton);
  92.         buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
  93.  
  94.         add(listScrollPane, BorderLayout.CENTER);
  95.         add(buttonPane, BorderLayout.PAGE_END);
  96.     }
  97.  
  98.     class FireListener implements ActionListener {
  99.         public void actionPerformed(ActionEvent e) {
  100.             //This method can be called only if
  101.             //there's a valid selection
  102.             //so go ahead and remove whatever's selected.
  103.             int index = list.getSelectedIndex();
  104.             listModel.remove(index);
  105.  
  106.             int size = listModel.getSize();
  107.  
  108.             if (size == 0) { //Nobody's left, disable firing.
  109.                 fireButton.setEnabled(false);
  110.  
  111.             } else { //Select an index.
  112.                 if (index == listModel.getSize()) {
  113.                     //removed item in last position
  114.                     index--;
  115.                 }
  116.  
  117.                 list.setSelectedIndex(index);
  118.                 list.ensureIndexIsVisible(index);
  119.             }
  120.         }
  121.     }
  122.  
  123.     //This listener is shared by the text field and the hire button.
  124.     class HireListener implements ActionListener, DocumentListener {
  125.         private boolean alreadyEnabled = false;
  126.         private JButton button;
  127.  
  128.         public HireListener(JButton button) {
  129.             this.button = button;
  130.         }
  131.  
  132.         //Required by ActionListener.
  133.         public void actionPerformed(ActionEvent e) {
  134.             String name = employeeName.getText();
  135.  
  136.             //User didn't type in a unique name...
  137.             if (name.equals("") || alreadyInList(name)) {
  138.                 Toolkit.getDefaultToolkit().beep();
  139.                 employeeName.requestFocusInWindow();
  140.                 employeeName.selectAll();
  141.                 return;
  142.             }
  143.  
  144.             int index = list.getSelectedIndex(); //get selected index
  145.             if (index == -1) { //no selection, so insert at beginning
  146.                 index = 0;
  147.             } else {           //add after the selected item
  148.                 index++;
  149.             }
  150.  
  151.             listModel.insertElementAt(employeeName.getText(), index);
  152.             //If we just wanted to add to the end, we'd do this:
  153.             //listModel.addElement(employeeName.getText());
  154.  
  155.             //Reset the text field.
  156.             employeeName.requestFocusInWindow();
  157.             employeeName.setText("");
  158.  
  159.             //Select the new item and make it visible.
  160.             list.setSelectedIndex(index);
  161.             list.ensureIndexIsVisible(index);
  162.         }
  163.  
  164.         //This method tests for string equality. You could certainly
  165.         //get more sophisticated about the algorithm.  For example,
  166.         //you might want to ignore white space and capitalization.
  167.         protected boolean alreadyInList(String name) {
  168.             return listModel.contains(name);
  169.         }
  170.  
  171.         //Required by DocumentListener.
  172.         public void insertUpdate(DocumentEvent e) {
  173.             enableButton();
  174.         }
  175.  
  176.         //Required by DocumentListener.
  177.         public void removeUpdate(DocumentEvent e) {
  178.             handleEmptyTextField(e);
  179.         }
  180.  
  181.         //Required by DocumentListener.
  182.         public void changedUpdate(DocumentEvent e) {
  183.             if (!handleEmptyTextField(e)) {
  184.                 enableButton();
  185.             }
  186.         }
  187.  
  188.         private void enableButton() {
  189.             if (!alreadyEnabled) {
  190.                 button.setEnabled(true);
  191.             }
  192.         }
  193.  
  194.         private boolean handleEmptyTextField(DocumentEvent e) {
  195.             if (e.getDocument().getLength() <= 0) {
  196.                 button.setEnabled(false);
  197.                 alreadyEnabled = false;
  198.                 return true;
  199.             }
  200.             return false;
  201.         }
  202.     }
  203.  
  204.     //This method is required by ListSelectionListener.
  205.     public void valueChanged(ListSelectionEvent e) {
  206.         if (e.getValueIsAdjusting() == false) {
  207.  
  208.             if (list.getSelectedIndex() == -1) {
  209.             //No selection, disable fire button.
  210.                 fireButton.setEnabled(false);
  211.  
  212.             } else {
  213.             //Selection, enable the fire button.
  214.                 fireButton.setEnabled(true);
  215.             }
  216.         }
  217.     }
  218.  
  219.     /**
  220.      * Create the GUI and show it.  For thread safety,
  221.      * this method should be invoked from the
  222.      * event-dispatching thread.
  223.      */
  224.     private static void createAndShowGUI() {
  225.         //Create and set up the window.
  226.         JFrame frame = new JFrame("ListDemo");
  227.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  228.  
  229.         //Create and set up the content pane.
  230.         JComponent newContentPane = new ListDemo();
  231.         newContentPane.setOpaque(true); //content panes must be opaque
  232.         frame.setContentPane(newContentPane);
  233.  
  234.         //Display the window.
  235.         frame.pack();
  236.         frame.setVisible(true);
  237.     }
  238.  
  239.     public static void main(String[] args) {
  240.         //Schedule a job for the event-dispatching thread:
  241.         //creating and showing this application's GUI.
  242.         javax.swing.SwingUtilities.invokeLater(new Runnable() {
  243.             public void run() {
  244.                 createAndShowGUI();
  245.             }
  246.         });
  247.     }
  248. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement