如何在Java Swing的组合框中添加分隔符

说明

以下示例展示了如何在Java Swing的组合框中添加分隔符。

我们正在使用以下 API。

  • JComboBox : 创建标准组合框。

  • JCheckBox.setRenderer(renderer); : 设置处理 JSeparator 的自定义渲染器。

  • ListCellRenderer : 为组合框创建自定义单元格渲染器。

代码示例

package com.yiidian;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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"};
      
      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;
   }   
}

执行效果如下:

热门文章

优秀文章