如何在swing中建立多區間選擇列表框?

2019-10-16 22:04:20

下面的範例展示了如何在Java Swing應用程式中建立多間隔列表框。多區間可以以任何方式選擇多個專案。

使用以下API -

  • JList - 建立標準列表。
  • JList.setSelectedIndex(index); - 選擇專案。
  • JList.setSelectionMode(); - 設定選擇模式。

範例

package com.yiibai.swingdemo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("在swing中建立多區間選擇列表框");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      String[] numbers = {"Java", "Python", "Csharp", "MySQL", "Oracle"};
      JList<String> listBox = new JList<>(numbers);
      listBox.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      listBox.setVisibleRowCount(-1); // to keep all values visible
      listBox.setSelectedIndex(3);
      listBox.addListSelectionListener(new ListSelectionListener() {        
         @Override
         public void valueChanged(ListSelectionEvent e) {
            JList list = (JList)e.getSource();            
            JOptionPane.showMessageDialog(frame,list.getSelectedValue());
         }
      });

      panel.add(listBox);   
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}

執行上面範例程式碼,得到以下結果: