目前开发项目由于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);
。。。