2011-02-20 5 views
4

JComboboxの矢印JButtonにイベントをアタッチしようとしています。JComboBoxのアクションイベントをアタッチするJButton

だから私は、カスタムComboBoxUIを行います、これに伴う問題は、コンボボックスの見た目が異なることである

public class CustomBasicComboBoxUI extends BasicComboBoxUI { 

    public static CustomBasicComboBoxUI createUI(JComponent c) { 
     return new CustomBasicComboBoxUI(); 
    } 

    @Override 
    protected JButton createArrowButton() { 
     JButton button=super.createArrowButton(); 
     if(button!=null) { 
      button.addActionListener(new ActionListener() { 

       public void actionPerformed(ActionEvent e) { 
        // arrow button clicked 
       } 
      }); 
     } 
     return button; 
    } 
} 

古い見ているようです。 なぜですか?同じ矢印ボタンにリスナーを追加するだけです...

ありがとうございました。

答えて

4

おそらく問題は、JComboBoxがBasicComboBoxUIではなく、別のLook&Feelの1つ、おそらくMetalComboBoxUIであると考えているためです。

新しいCustomBasicComboBoxUIオブジェクトを作成するのではなく、既存のJComboBoxオブジェクトからJButtonコンポーネントを抽出できますか?すなわち、

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

import javax.swing.*; 

public class ComboBoxArrowListener { 
    private static void createAndShowUI() { 
     String[] data = {"One", "Two", "Three"}; 
     JComboBox combo = new JComboBox(data); 
     JPanel panel = new JPanel(); 
     panel.add(combo); 

     JButton arrowBtn = getButtonSubComponent(combo); 
     if (arrowBtn != null) { 
     arrowBtn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("arrow button pressed"); 
      } 
     }); 
     } 

     JFrame frame = new JFrame("ComboBoxArrowListener"); 
     frame.getContentPane().add(panel); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    private static JButton getButtonSubComponent(Container container) { 
     if (container instanceof JButton) { 
     return (JButton) container; 
     } else { 
     Component[] components = container.getComponents(); 
     for (Component component : components) { 
      if (component instanceof Container) { 
       return getButtonSubComponent((Container)component); 
      } 
     } 
     } 
     return null; 
    } 

    public static void main(String[] args) { 
     java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowUI(); 
     } 
     }); 
    } 
} 
+0

こんにちは、ありがとう!これは私が必要なものです。 – blow

+0

あなたは大歓迎です! –

関連する問題