自定义swing.JComboBox下拉事件

      目前开发项目由于swt的兼容问题,因此使用swing开发,需要通过JComboBox实现可编辑并可下拉选择文件路径的效果,网上只介绍了实现方法,我分享一下源码,新人理解不对请见谅。

      派生MetalComboBoxUI,MetalComboBoxUI有默认显示样式,使用网上说的BasicComboBoxUI没样式了。重载BasicComboBoxUI的configureArrowButton()删除原有事件并添加自定义事件。对底层不理解,将JComboBox传入单纯为了方便。

/

 

package tool.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalComboBoxUI;

 

//自定义ComboBox显示效果
public class FileComboBoxUI extends MetalComboBoxUI
{
 private JComboBox component;
 public static ComponentUI createUI(JComboBox c)
 {
        return new FileComboBoxUI(c);
    }
 
 public FileComboBoxUI(JComboBox c)
 {
  component = c;
    }
 
    static final StringBuffer HIDE_POPUP_KEY = new StringBuffer("HidePopupKey");
   
    @Override
    public void configureArrowButton()
    {
        if ( arrowButton != null )
        {
         arrowButton.setEnabled( comboBox.isEnabled() );
         arrowButton.setFocusable(comboBox.isFocusable());
         arrowButton.setRequestFocusEnabled(false);
           
            //替换原下拉按钮鼠标事件
            //arrowButton.addMouseListener( popup.getMouseListener() );
            //arrowButton.addMouseMotionListener( popup.getMouseMotionListener() );
            arrowButton.addActionListener(new ActionListener()
            {

                 //修改事件为选择目录
                 public void actionPerformed(final ActionEvent e)
                {
                       JFileChooser chooser = new JFileChooser();
                       chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
     
                      //chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                     //chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Image Files", "jpg"));
     
                      int returnVal = chooser.showOpenDialog(null);
                      if(returnVal == JFileChooser.APPROVE_OPTION)
                     {

                          component.removeAllItems();
                          component.addItem(chooser.getSelectedFile().getAbsolutePath());
                     }
                }
            });

 

 

            arrowButton.resetKeyboardActions();
            arrowButton.putClientProperty("doNotCancelPopup", HIDE_POPUP_KEY);
            arrowButton.setInheritsPopupMenu(true);
        }
    }
}

 

 

 

//

//使用

。。。

JComboBox comboFile = new JComboBox();
comboFile.setUI(new FileComboBoxUI(comboFile) );

comboFile.setEditable(true);

。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值