2009-07-03 7 views
1

Je voudrais créer JComboBox contrôle similaire à la zone de texte URL de Firefox. Est-ce que quelqu'un sait comment personnaliser le champ de texte du JComboBox. Je veux ajouter quelques icônes sur le ALIGN.HORIZONTAL_RIGHT près du bouton fléché des JComboBoxComment ajouter une icône près de flèche pour JComboBox


Merci pour votre explication très détail. En fait, je vais combiner DefaultListCellRenderer et ajouter l'icône à la zone de liste déroulante comme code suivant

import java.awt.Dimension; 
import java.awt.Insets; 
import javax.swing.JButton; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

public class Main extends JFrame { 
    public Main() { 
     // Create icon "C" 
     JButton jb = new JButton("C"); 
     jb.setMargin(new Insets(0, 0, 0, 0)); 
     jb.setBounds(245, 2, 18, 18); 

     // Create combo box 
     String[] languages = new String[]{"Java", "C#", "PHP"}; 
     JComboBox jc = new JComboBox(languages); 
     // jc.setEditable(true); 
     jc.add(jb); 

     getContentPane().add(jc); 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setSize(new Dimension(300, 58)); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     final Main main = new Main(); 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       main.setVisible(true); 
      } 
     }); 
    } 
} 

Mais quand je mets jc.setEditable(true); l'éditeur de combo a caché mon icône. Je pense à une autre façon de simuler Firefox barre impressionnante. Avez-vous une idée pour cela?

Répondre

2

est complété par exemple ici que le démontrent:

package com.demo.combo.icon; 



import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.event.WindowAdapter; 
import java.awt.event.WindowEvent; 
import java.util.HashMap; 
import java.util.Map; 

import javax.swing.DefaultListCellRenderer; 
import javax.swing.Icon; 
import javax.swing.ImageIcon; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JList; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 


public class ShowConboWithIcons extends JFrame { 

private static final long serialVersionUID = 1L; 

private static final ImageIcon INFO_ICON = new ImageIcon("info.png"); 
private static final ImageIcon NONE_ICON = new ImageIcon("none.png"); 
public final String NONE_STR = "None"; 
private final String INFO_STR = "Info"; 

private JComboBox comboBox; 
private JPanel topPanel; 

private String[] str_arr = null; 


public ShowConboWithIcons(String[] str_arr) { 
    this.str_arr = str_arr;  
} 


public void createGUI(){ 

    setMinimumSize(new Dimension(100,100)); 
    setTitle("Demo"); 
    setLocation(200, 200); 

    topPanel = new JPanel(); 
    getContentPane().add(topPanel, BorderLayout.CENTER); 

    Map<Object, Icon> icons = new HashMap<Object, Icon>(); 

    icons.put(NONE_STR, NONE_ICON); 
    icons.put(INFO_STR, INFO_ICON); 

    comboBox = new JComboBox(); 
    comboBox.setRenderer(new IconListRenderer(icons)); 
    comboBox.addItem("None"); 

    for(String val : str_arr){ 
     comboBox.addItem(val); 
    } 

    topPanel.add(comboBox); 

    super.addWindowListener(new WindowAdapter() {   
     public void windowClosing(WindowEvent e) {    
      dispose();   
     }   
    }); 
} 

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { 

    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 

    String[] str_arr = {"A", "B", "C", "D", "E"}; 

    ShowConboWithIcons T = new ShowConboWithIcons(str_arr); 
    T.createGUI(); 
    T.setVisible(true);   
} 


class IconListRenderer extends DefaultListCellRenderer{ 
    private static final long serialVersionUID = 1L; 
    private Map<Object, Icon> icons = null; 

    public IconListRenderer(Map<Object, Icon> icons){ 
     this.icons = icons; 
    } 

    @Override 
    public Component getListCellRendererComponent(JList list, Object value, int index,boolean isSelected, boolean cellHasFocus) 
    { 
     JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 

     // Get icon to use for the list item value 
     Icon icon = icons.get(value); 

     if(!value.toString().equals(NONE_STR)){ 
      icon = icons.get(INFO_STR); 
     } 

     // Set icon to display for value 
     label.setIcon(icon); 
     return label; 
    } 
} 
} 

Preview:

combo default mode:

combo select item:

5

Pour modifier le rendu d'un composant, vous travaillez généralement avec ce que l'on appelle Renderer s. Pour la liste déroulante, voir comment créer un custom combobox renderer. Juste un coup d'œil rapide, mais pour votre cas, une simple configuration de DefaultListCellRenderer peut suffire, puisque vous pouvez définir les propriétés JLabel pour positionner le texte sur l'image. Si ce n'est pas le cas, étendez-le simplement. Souvenez-vous également que vous devez définir un modèle qui inclut l'icône afin que le moteur de rendu de la zone de liste déroulante puisse l'obtenir - vous pouvez également créer un ComboBoxModel personnalisé, en fonction de votre objet de données.

+0

Salut aberrant80, Merci pour votre réponse rapide. J'ai vérifié le DefaultListCellRenderer, cela m'aidera à personnaliser l'élément de la liste comme Firefox. Mais l'autre pour ajouter l'icône dans la boîte de texte JComboBox, j'utiliserai la peinture personnalisée pour dessiner une icône qui devrait être sur la droite du contrôle. http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html Merci, Minh – Minh

+1

@minh, pour la zone de texte, vous devriez voir ce que vous pouvez faire en créant un éditeur. il y a une mention dans le tutoriel @ aberrant80 posté. – akf

+0

DefaultListCellRenderer est essentiellement un JLabel. JLabel prend en charge une icône en plus du texte normal. Je suppose qu'il devrait simplement récupérer le moteur de rendu et ensuite définir le positionnement/l'alignement approprié de l'icône au texte et cela pourrait fonctionner. – aberrant80

Questions connexes