Swing下拉复选框菜单

首先放成品的展示图




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

---这是因为我教授看了我之前做的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);
        


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值