De Coderanch et Sun Forum, je connais la technique d'avoir une barre de défilement horizontale pour JComboBox. Cependant, leur solution suggérée est limitée à Look n Feel spécifique. Comme vous pouvez le voir, l'extrait de code de clé ci-dessous ne fonctionnera pas correctement, si les utilisateurs sont sous Linux avec GTK + look n feel, ou Windows avec Nimbus look n feel.Portable façon d'avoir une barre de défilement horizontale pour JComboBox
Comment je peux avoir un moyen portable, pour faire JComboBox capable d'avoir une barre de défilement horizontale?
Le code source complet est AutoCompleteJComboBox.java
L'extrait de code sont les suivantes:
package org.yccheok.jstock.gui;
public class AutoCompleteJComboBox extends JComboBox {
@Override
public void setUI(ComboBoxUI ui)
{
if (ui != null)
{
// Let's try our own customized UI.
Class c = ui.getClass();
final String myClass = "org.yccheok.jstock.gui.AutoCompleteJComboBox$My" + c.getSimpleName();
try {
ComboBoxUI myUI = (ComboBoxUI) Class.forName(myClass).newInstance();
super.setUI(myUI);
return;
} catch (ClassNotFoundException ex) {
log.error(null, ex);
} catch (InstantiationException ex) {
log.error(null, ex);
} catch (IllegalAccessException ex) {
log.error(null, ex);
}
}
// Either null, or we fail to use our own customized UI.
// Fall back to default.
super.setUI(ui);
}
// This is a non-portable method to make combo box horizontal scroll bar.
// Whenever there is a new look-n-feel, we need to manually provide the ComboBoxUI.
// Any idea on how to make this portable?
//
protected static class MyWindowsComboBoxUI extends com.sun.java.swing.plaf.windows.WindowsComboBoxUI
{
@Override
protected ComboPopup createPopup()
{
return new MyComboPopup(comboBox);
}
}
protected static class MyMotifComboBoxUI extends com.sun.java.swing.plaf.motif.MotifComboBoxUI
{
@Override
protected ComboPopup createPopup()
{
return new MyComboPopup(comboBox);
}
}
protected static class MyMetalComboBoxUI extends javax.swing.plaf.metal.MetalComboBoxUI
{
@Override
protected ComboPopup createPopup()
{
return new MyComboPopup(comboBox);
}
}
private static class MyComboPopup extends BasicComboPopup
{
public MyComboPopup(JComboBox combo)
{
super(combo);
}
@Override
public JScrollPane createScroller()
{
return new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
}
}