Swing下拉复选框菜单

5 篇文章 0 订阅

首先放成品的展示图




就是这样的一个小插件。其实网上挺多示例代码的。但是为什么我花了不少时间在上面呢?

---这是因为我教授看了我之前做的web的项目,用JS你可以写出一个像这样的的框(下图)


看最上面那个框,颜色不一样的。没错,它像一个父节点一样,可以控制全选与全不选。


于是我手动加了一个“Select ALL”。不过我找了很久也找不到怎么样判断下拉菜单已经收回去了,而我又没有那么多时间,所以我最后放弃了让他自行判断,还是多加了两个button在最下方。

这个判断下拉菜单的弹出与收回的暂时留在future work里面吧。



组件的代码有参考别人的,但是我忘记哪里看的了。。。所以虽然标明转载但是忘记出处了

package UserInterface;
import java.awt.BorderLayout;  
import java.awt.GridLayout;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;  
import java.util.List;  
  


import javax.swing.JButton;  
import javax.swing.JCheckBox;  
import javax.swing.JPanel;  
import javax.swing.JPopupMenu;  
  
public class MultiPopup extends JPopupMenu {  
  
    private List<ActionListener> listeners = new ArrayList<ActionListener>();  
  
    private Object[] values;  
      
    private Object[] defaultValues;  
      
    private List<JCheckBox> checkBoxList = new ArrayList<JCheckBox>();  
      
    private JButton commitButton ;  
      
    private JButton cancelButton;  
      
    public static final String COMMIT_EVENT = "commit";  
      
    public static final String CANCEL_EVENT = "cancel";  
      
    public MultiPopup(Object[] value , Object[] defaultValue) {  
        super();  
        values = value;  
        defaultValues = defaultValue;  
        initComponent();  
    }  
  
    public void addActionListener(ActionListener listener) {  
        if (!listeners.contains(listener))  
            listeners.add(listener);  
    }  
  
    public void removeActionListener(ActionListener listener) {  
        if (listeners.contains(listener))  
            listeners.remove(listener);  
    }  
  
    private void initComponent() {  
          
        JPanel checkboxPane = new JPanel();  
          
        JPanel buttonPane = new JPanel();  
          
        this.setLayout(new BorderLayout());  
          
          
        for(Object v : values){  
            JCheckBox temp = new JCheckBox(v.toString() , selected(v));  
            checkBoxList.add(temp);  
        }  
        
        if(checkBoxList.get(0).getText().equals("Selected All"))
        	checkBoxList.get(0).addItemListener(new ItemListener() 
        { 
    	       public void itemStateChanged(ItemEvent e) 
    	       { 
    	    	   System.out.println("被选中状态   "+checkBoxList.get(0).isSelected());
    	    	   if(checkBoxList.get(0).isSelected())//Select All 被选中
    	    	   {
    	    		   //检查其他的是否被选中乳沟没有就选中他们
    	    		   for(int i=1; i< checkBoxList.size();i++)
    	    		   {
    	    			   if(!checkBoxList.get(i).isSelected())
    	    				   checkBoxList.get(i).setSelected(true);
    	    		   }
    	    	   }
    	    	   else
    	    	   {
    	    		   for(int i=1; i< checkBoxList.size();i++)
    	    		   {
    	    			   if(checkBoxList.get(i).isSelected())
    	    				   checkBoxList.get(i).setSelected(false);
    	    		   }
    	    	   }
    	       }  
    	     });
        
        
        
        checkboxPane.setLayout(new GridLayout(checkBoxList.size() , 1 ,3, 3));  
        for(JCheckBox box : checkBoxList){  
            checkboxPane.add(box);  
        }  
          
        commitButton = new JButton("ok");  
          
        commitButton.addActionListener(new ActionListener(){  
  
            public void actionPerformed(ActionEvent e) {  
                commit();  
            }  
              
        });  
          
        cancelButton = new JButton("cancel");  
          
        cancelButton.addActionListener(new ActionListener(){  
  
            public void actionPerformed(ActionEvent e) {  
                cancel();  
            }  
              
        });  
          
        buttonPane.add(commitButton);  
          
        buttonPane.add(cancelButton);  
          
        this.add(checkboxPane , BorderLayout.CENTER);  
          
        this.add(buttonPane , BorderLayout.SOUTH);  
          
          
    }  
  
    private boolean selected(Object v) {  
        for(Object dv : defaultValues){  
            if( dv .equals(v) ){  
                return true;  
            }  
        }  
        return false;  
    }  
  
    protected void fireActionPerformed(ActionEvent e) {  
        for (ActionListener l : listeners) {  
            l.actionPerformed(e);  
        }  
    }  
      
    public Object[] getSelectedValues(){  
        List<Object> selectedValues = new ArrayList<Object>(); 
       
        if(checkBoxList.get(0).getText().equals("Selected All"))
        {
        	if(checkBoxList.get(0).isSelected())
        	{
        		for(int i = 1 ; i < checkBoxList.size() ; i++)
    		 {
    			 selectedValues.add(values[i]);
    		 }
        	}
        	else
        	{
        		for(int i = 1 ; i < checkBoxList.size() ; i++){  
                	
                	if(checkBoxList.get(i).isSelected())  
                        selectedValues.add(values[i]);  
                }  
        	}
        }else
        	for(int i = 0 ; i < checkBoxList.size() ; i++){  
        	
        	if(checkBoxList.get(i).isSelected())  
                selectedValues.add(values[i]);  
        }  
        
        
        return selectedValues.toArray(new Object[selectedValues.size()]);  
    }  
  
    public void setDefaultValue(Object[] defaultValue) {  
        defaultValues = defaultValue;  
          
    }  
      
    public void commit(){  
        fireActionPerformed(new ActionEvent(this, 0, COMMIT_EVENT));  
    }  
      
    public void cancel(){  
        fireActionPerformed(new ActionEvent(this, 0, CANCEL_EVENT));  
    }  
  
}  

package UserInterface;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicArrowButton;

public class MultiComboBox extends JComponent {

	private Object[] values;

	public Object[] defaultValues;
	
	private List<ActionListener> listeners = new ArrayList<ActionListener>();
	
	private MultiPopup popup;
	
	private JTextField editor;
	
	protected JButton   arrowButton;
	
	private String valueSperator;
	
	private static final String DEFAULT_VALUE_SPERATOR = ","; 

	public MultiComboBox(Object[] value, Object[] defaultValue){
		this(value,defaultValue,DEFAULT_VALUE_SPERATOR);
	}
	
	public MultiComboBox(Object[] value, Object[] defaultValue , String valueSperator) {
		values = value;
		defaultValues = defaultValue;
		this.valueSperator = valueSperator;
		initComponent();
	}

	private void initComponent() {
		//暂时使用该布局,后续自己写个布局
		this.setLayout(new FlowLayout());
		popup =new  MultiPopup(values,defaultValues);
		popup.addActionListener(new PopupAction());
		editor = new JTextField();
		editor.setBackground(Color.WHITE);
		editor.setEditable(false);
		editor.setPreferredSize(new Dimension(150,20));
//		editor.setBorder(getBorder());
		editor.addMouseListener(new EditorHandler());
		arrowButton = createArrowButton();
		arrowButton.addMouseListener(new EditorHandler());
		add(editor);
		add(arrowButton);
		setText() ;
		
		
	}

	public Object[] getSelectedValues() {
		return popup.getSelectedValues();
	}
	
	public void addActionListener(ActionListener listener) {
		if (!listeners.contains(listener))
			listeners.add(listener);
	}

	public void removeActionListener(ActionListener listener) {
		if (listeners.contains(listener))
			listeners.remove(listener);
	}
	
	protected void fireActionPerformed(ActionEvent e) {
		for (ActionListener l : listeners) {
			l.actionPerformed(e);
		}
	}
	
	private class PopupAction implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			
			if(e.getActionCommand().equals(MultiPopup.CANCEL_EVENT)){
				
			}else if(e.getActionCommand().equals(MultiPopup.COMMIT_EVENT)){
				defaultValues = popup.getSelectedValues();
				setText();
				//把事件继续传递出去
				fireActionPerformed(e);
			}
			
			togglePopup();
			
			
		}

	}
	
	private void togglePopup(){
		if(popup.isVisible()){
			popup.setVisible(false);
		}else{
			popup.setDefaultValue(defaultValues);
			popup.show(this, 0, getHeight());
		}
	}
	
	private void setText() {
		StringBuilder builder = new StringBuilder();
		for(Object dv : defaultValues){
			builder.append(dv);
			builder.append(valueSperator);
		}
		
		editor.setText(builder.substring(0, builder.length() > 0 ? builder.length() -1  : 0).toString());		
	}
	
	private class EditorHandler implements MouseListener{

		public void mouseClicked(MouseEvent e) {
			togglePopup();
		}

		public void mousePressed(MouseEvent e) {
			
		}

		public void mouseReleased(MouseEvent e) {
			
		}

		public void mouseEntered(MouseEvent e) {
			
		}

		public void mouseExited(MouseEvent e) {
			
		}
		
	}
	
	
	  public void paintComponent(Graphics g){
	        g.setColor(Color.white);
	        g.fillRect(0,0,getWidth(),getHeight());
	    }
	  
	  
	    protected JButton createArrowButton() {
	        JButton button = new BasicArrowButton(BasicArrowButton.SOUTH,
	                                    UIManager.getColor("ComboBox.buttonBackground"),
	                                    UIManager.getColor("ComboBox.buttonShadow"),
	                                    UIManager.getColor("ComboBox.buttonDarkShadow"),
	                                    UIManager.getColor("ComboBox.buttonHighlight"));
	        button.setName("ComboBox.arrowButton");
	        return button;
	    }
	    
	   private class MulitComboboxLayout  implements LayoutManager{

			public void addLayoutComponent(String name, Component comp) {
				// TODO Auto-generated method stub
				
			}

			public void removeLayoutComponent(Component comp) {
				// TODO Auto-generated method stub
				
			}

			public Dimension preferredLayoutSize(Container parent) {
				return parent.getPreferredSize();
			}

			public Dimension minimumLayoutSize(Container parent) {
				return parent.getMinimumSize();
			}

			public void layoutContainer(Container parent) {
				int w=parent.getWidth();
	            int h=parent.getHeight();
	            Insets insets=parent.getInsets();
	            h=h-insets.top-insets.bottom;
				
			}
	    	
	    }

}


调用如下~

        JLabel label3 = new JLabel("Media Outlets:");
        Object[] value = new String[]{ "Selected All","Al-Jazeera" , "BBC News" ,"Daily Mail" ,"Fox News","New York Daily News", "New York Times","the Guardian","Wall Street Journal"};  
        Object[] defaultValue = new String[]{ "Selected All" }; 
        
        MultiComboBox mulit = new MultiComboBox(value, defaultValue);
        


  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Java 图形界面开发简介 .............. ................................ ................................ ..... 5 1. Swing1. Swing1. Swing 1. Swing1. Swing1. Swing1. Swing简介 ................................ ................................ ................................ ................................ ............... 5 2. Swing2. Swing2. Swing 2. Swing2. Swing2. Swing2. Swing组件 ................................ ................................ ................................ ................................ ............... 5 3. 3. 3. 布局管理器 布局管理器 ................................ ................................ ................................ ................................ ............. 8 4. 4. 4. 代码实例 代码实例 : 一个简单的窗口程序 一个简单的窗口程序 一个简单的窗口程序 一个简单的窗口程序 一个简单的窗口程序 ................................ ................................ ................................ ..... 9 1.1: FlowLayo1.1: FlowLayo1.1: FlowLayo1.1: FlowLayo1.1: FlowLayo 1.1: FlowLayo 1.1: FlowLayout (流式布局) (流式布局) (流式布局) (流式布局) ................................ ................................ ................................ ...................... 10 1. 概述 ................................ ................................ ................................ ................................ ....................... 10 2. 代码实例 ................................ ................................ ................................ ................................ .............. 11 1.2: GridLayout(网格布局) (网格布局) (网格布局) (网格布局) ................................ ................................ ................................ ..................... 13 1. 概述 ................................ ................................ ................................ ................................ ....................... 13 2. 代码演示 ................................ ................................ ................................ ................................ .............. 14 1.3: GridBagLayout1.3: GridBagLayout1.3: GridBagLayout1.3: GridBagLayout1.3: GridBagLayout 1.3: GridBagLayout 1.3: GridBagLayout1.3: GridBagLayout 1.3: GridBagLayout1.3: GridBagLayout 1.3: GridBagLayout1.3: GridBagLayout(网格袋布局) (网格袋布局) (网格袋布局) (网格袋布局) ................................ ................................ ................................ ........... 17 1. 布局 : GridBagLayout ................................ ................................ ................................ ...................... 17 2. 约束 : GridBagConstraints ................................ ................................ ................................ ............. 17 3. 属性 : GridBagConstraints 的属性 ................................ ................................ ............................. 18 4. 案例 : GridBagLayout使用实例 使用实例 ................................ ................................ ................................ ... 19 1.4: BoxLayout1.4: BoxLayout1.4: BoxLayout1.4: BoxLayout1.4: BoxLayout 1.4: BoxLayout1.4: BoxLayout1.4: BoxLayout 1.4: BoxLayout1.4: BoxLayout(箱式布局) (箱式布局) (箱式布局) (箱式布局) ................................ ................................ ................................ ........................ 25 1. 概述 ................................ ................................ ................................ ................................ ....................... 25 2. 代码实例 ................................ ................................ ................................ ................................ .............. 27 1.5: GroupLayout(分组布局) (分组布局) (分组布局) ................................ ................................ ................................ ................. 29 1. 概述 ................................ ................................ ................................ ................................ ....................... 29 2. 代码实例 ................................ ................................ ................................ ................................ .............. 31 1.6: CardLayout(卡片布局) (卡片布局) (卡片布局) ................................ ................................ ................................ .................... 36 1. 概述 ................................ ................................ ................................ ................................ ....................... 36 2. 代码实例 ................................ ................................ ................................ ................................ .............. 37 1.7: BorderLayout(边界布局) (边界布局) (边界布局) ................................ ................................ ................................ ................ 40 1. 概述 ................................ ................................ ................................ ................................ ....................... 40 2. 代码实例 ................................ ................................ ................................ ................................ .............. 41 1.8: SpringLayout(弹性布局) (弹性布局) (弹性布局) ................................ ................................ ................................ ................ 43 1. 概述 ................................ ................................ ................................ ................................ ....................... 43 2. 代码实例 ................................ ................................ ................................ ................................ .............. 47 1.9: null(绝对布局) (绝对布局) (绝对布局) ................................ ................................ ................................ ................................ .... 52 1. 概述 ................................ ................................ ................................ ................................ ....................... 52 2. 代码实例 ................................ ................................ ................................ ................................ .............. 53 2.1: JLabel(标签) (标签) (标签) ................................ ................................ ................................ ................................ ....... 56 1. 概述 ................................ ................................ ................................ ................................ ....................... 56 2. 代码实例 ................................ ................................ ................................ ................................ .............. 61 2.2: JButton(按钮) (按钮) (按钮) ................................ ................................ ................................ ................................ ..... 64 1. 概述 ................................ ................................ ................................ ................................ ....................... 64 2. 代码实例 : 默认按钮 默认按钮 ................................ ................................ ................................ ........................ 66 3. 代码实例 : 自定义图片按钮 自定义图片按钮 自定义图片按钮 自定义图片按钮 ................................ ................................ ................................ .......... 68 2.3: JRadioButton(单选按钮) (单选按钮) (单选按钮) ................................ ................................ ................................ ................ 71 2 1. 概述 ................................ ................................ ................................ ................................ ....................... 71 2. 代码实例 ................................ ................................ ................................ ................................ .............. 73 2.4: JCheckBox(复选框) (复选框) (复选框) ................................ ................................ ................................ ......................... 75 1. 概述 ................................ ................................ ................................ ................................ ....................... 75 2. 代码实例 ................................ ................................ ................................ ................................ .............. 77 2.5: JToggleButton(开关按钮) (开关按钮) (开关按钮) ................................ ................................ ................................ .............. 80 1. 概述 ................................ ................................ ................................ ................................ ....................... 80 2. 代码实例 : 默认 的开关按钮 的开关按钮 的开关按钮 ................................ ................................ ................................ .......... 82 3. 代码实例 : 自定义图片开关 自定义图片开关 自定义图片开关 自定义图片开关 ................................ ................................ ................................ .......... 84 2.6: JTextField(文本框) (文本框) (文本框) ................................ ................................ ................................ ........................... 87 1. 概述 ................................ ................................ ................................ ................................ ....................... 87 2. 实例代码 ................................ ................................ ................................ ................................ .............. 91 2.7:PasswordField(密码框) (密码框) (密码框) ................................ ................................ ................................ ................... 93 1. 概述 ................................ ................................ ................................ ................................ ....................... 93 2. 代码实例 ................................ ................................ ................................ ................................ .............. 96 2.8: JTextArea(文本区域) (文本区域) (文本区域) (文本区域) ................................ ................................ ................................ ....................... 98 1. 概述 ................................ ................................ ................................ ................................ ....................... 98 2. 代码实例 ................................ ................................ ................................ ................................ ............ 103 2.9: JComboBox(下拉列表框) (下拉列表框) (下拉列表框) ................................ ................................ ................................ ............ 105 1. 概述 ................................ ................................ ................................ ................................ ..................... 105 2. 代码实例 ................................ ................................ ................................ ................................ ............ 107 2.10: JList(列 表框) 表框) ................................ ................................ ................................ ................................ .. 110 1. 概述 ................................ ................................ ................................ ................................ ..................... 110 2. 代码实例 ................................ ................................ ................................ ................................ ............ 113 2.11: JProgressBar(进度条) (进度条) (进度条) ................................ ................................ ................................ ................ 117 1. 概述 ................................ ................................ ................................ ................................ ..................... 117 2. 代码实例 ................................ ................................ ................................ ................................ ............ 119 2.12: JSlider(滑块) (滑块) (滑块) ................................ ................................ ................................ ................................ .. 123 1. 概述 ................................ ................................ ................................ ................................ ..................... 123 2. 代码实例 : 默认刻度值 默认刻度值 默认刻度值 ................................ ................................ ................................ .................. 126 3. 代码实例 : 自定义标签刻度值 自定义标签刻度值 自定义标签刻度值 自定义标签刻度值 ................................ ................................ ................................ .... 128 3.1: JPanel(面板) (面板) ................................ ................................ ................................ ................................ ..... 132 1. 概述 ................................ ................................ ................................ ................................ ..................... 132 2. 代码实例 ................................ ................................ ................................ ................................ ............ 133 3.2: JScrollPane(滚动面板) (滚动面板) (滚动面板) (滚动面板) ................................ ................................ ................................ ................. 135 1. 概述 ................................ ................................ ................................ ................................ ..................... 135 2. 代码实例 ................................ ................................ ................................ ................................ ............ 138 3.2: JScrollPane(滚动面板) (滚动面板) (滚动面板) (滚动面板) ................................ ................................ ................................ ................. 140 1. 概述 ................................ ................................ ................................ ................................ ..................... 140 2. 代码实例 ................................ ................................ ................................ ................................ ............ 142 3.4: JTabbedPane(选项卡面板) (选项卡面板) (选项卡面板) (选项卡面板) ................................ ................................ ................................ ......... 145 1. 概述 ................................ ................................ ................................ ................................ ..................... 145 2. 代码实例 ................................ ................................ ................................ ................................ ............ 149 3.5: JLayeredPane(层级面板) (层级面板) (层级面板) ................................ ................................ ................................ ............
Swing 中,你可以使用 JComboBox 类创建下拉列表框,然后使用它的 addItem() 方法添加选项。如果你想要添加复选框下拉列表框中,你可以使用自定义的下拉列表框渲染器来实现。 以下是一个示例代码,它演示了如何在 JComboBox 中添加复选框: ``` import javax.swing.*; import javax.swing.plaf.basic.BasicComboBoxRenderer; import java.awt.*; public class ComboBoxExample extends JFrame { public ComboBoxExample() { setTitle("ComboBox Example"); setSize(300, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); // 创建一个 JPanel JPanel panel = new JPanel(); // 创建一个带有复选框的数组 JCheckBox[] checkBoxes = new JCheckBox[3]; checkBoxes[0] = new JCheckBox("Option 1"); checkBoxes[1] = new JCheckBox("Option 2"); checkBoxes[2] = new JCheckBox("Option 3"); // 创建一个自定义的下拉列表框渲染器 BasicComboBoxRenderer renderer = new BasicComboBoxRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof JCheckBox) { JCheckBox checkBox = (JCheckBox) value; setBackground(checkBox.getBackground()); setForeground(checkBox.getForeground()); setSelected(checkBox.isSelected()); setText(checkBox.getText()); } else { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } return this; } }; // 创建一个 JComboBox,并将自定义渲染器设置为其渲染器 JComboBox<JCheckBox> comboBox = new JComboBox<>(checkBoxes); comboBox.setRenderer(renderer); // 将 JComboBox 添加到面板中 panel.add(comboBox); // 将面板添加到 JFrame 中 getContentPane().add(panel); setVisible(true); } public static void main(String[] args) { new ComboBoxExample(); } } ``` 在这个例子中,我们创建了一个 JPanel,并创建了一个带有三个复选框的数组。然后,我们创建了一个自定义的下拉列表框渲染器,它会将复选框作为列表框的选项。接着,我们创建了一个 JComboBox,并将自定义渲染器设置为其渲染器。最后,我们将 JComboBox 添加到 JPanel 中,并将 JPanel 添加到 JFrame 中,并使其可见。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值