Swing 示例 - 在 ListBox 中添加分隔符



以下示例展示如何为 Java Swing 应用程序中的列表框创建分隔符。

我们使用以下 API。

  • JList − 创建标准列表。

  • JList.setSelectedIndex(index); − 选择一项。

  • JList.setSelectionMode(); − 设置选择模式。

  • JList.setCellRenderer(); − 设置自定义单元格渲染器,该渲染器会渲染分隔符。

示例

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
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.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.ListCellRenderer;
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 Tester");
      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);       

      Object[] numbers = {"One", "Two", "Three", 
    		  new JSeparator(JSeparator.HORIZONTAL),"Four", "Five"};
      JList<Object> listBox = new JList<>(numbers);
      listBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      listBox.setVisibleRowCount(-1); // to keep all values visible
      listBox.setSelectedIndex(3);
      ComboBoxRenderer renderer= new ComboBoxRenderer();
      renderer.setPreferredSize(new Dimension(100, 20));
      listBox.setCellRenderer(renderer);
      panel.add(listBox);   
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}
class ComboBoxRenderer extends JLabel implements ListCellRenderer<Object> {
   public Component getListCellRendererComponent(JList<? extends Object> list,
      Object value, int index, boolean isSelected, boolean cellHasFocus) {
         if(value instanceof JSeparator){
            return (Component)value;
         }else{
            setText(value.toString());
         }
         return this;
   }   
}

输出

Add Separator to ListBox
swingexamples_lists.htm
广告