如何在swing中的下拉式方塊中新增分隔符?

2019-10-16 22:05:31

下面的範例演示了如何在基於swing的應用程式中向下拉式方塊新增分隔符。

使用以下API -

  • JComboBox() - 建立標準下拉式方塊。
  • JCheckBox.setRenderer(renderer); - 設定處理JSeparator的自定義渲染器。
  • ListCellRenderer - 為下拉式方塊建立自定義單元格渲染器。

範例

package com.yiibai.swingdemo;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
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;

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);       
      Object[] numbers = {"Tw511.com", "Kaops.com", "Viibm.com", 
      new JSeparator(JSeparator.HORIZONTAL), "Baidu.com", "Google.com"};

      JComboBox<Object> comboBox = new JComboBox<>(numbers);
      comboBox.setSelectedIndex(1); 
      ComboBoxRenderer renderer= new ComboBoxRenderer();
      renderer.setPreferredSize(new Dimension(100, 20));
      comboBox.setRenderer(renderer);
      comboBox.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox)e.getSource();
            JOptionPane.showMessageDialog(frame,combo.getSelectedItem());

         }
      });

      panel.add(comboBox);   
      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;
   }   
}

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

組合框中添加分隔符