5

ユーザーが色を選択できる JComboBox があります。JComboBox は、テキストなしで色だけを表示しています。私はこの解決策を思いつきました。これが良いのか、避けるべきなのか、またその理由を教えてください。私は一般的にSwingとJavaに慣れていないので、しばらくお待ちください:)

public class ToolBar{
    private MainFrame mainFrame;

    public ToolBar (MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public JPanel getToolBar(){

        JPanel toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,2,2));
        toolbarPanel.setPreferredSize(new Dimension(mainFrame.getScreenWidth(),60));
        toolbarPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        JButton fillButton = new JButton("Fill: ");
        fillButton.setPreferredSize(new Dimension(60,20));
        //fillButton.setBackground(Color.red);
        toolbarPanel.add(fillButton);

        String[] test = {" ", " " , " " , " " , " " , " "};
        JComboBox colorBox = new JComboBox(test);
        colorBox.setMaximumRowCount(5);
        colorBox.setPreferredSize(new Dimension(50,20));
        colorBox.setRenderer(new MyCellRenderer());
        toolbarPanel.add(colorBox);

        return toolbarPanel;
    }
    class MyCellRenderer extends JLabel implements ListCellRenderer {  
         public MyCellRenderer() {  
             setOpaque(true);  
         }  
         public Component getListCellRendererComponent(  
             JList list,  
             Object value,  
             int index,  
             boolean isSelected,  
             boolean cellHasFocus)  
         {  
             setText(value.toString()); 
             switch (index) {
                case 0:  setBackground(Color.white);
                break;
                case 1:  setBackground(Color.red);
                break;
                case 2:  setBackground(Color.blue);
                break;
                case 3:  setBackground(Color.yellow);
                break;
                case 4:  setBackground(Color.green);
                break;
                case 5:  setBackground(Color.gray);
                break;
             }
             return this;  
         }  
    }
}

これは正常に動作します。JComboBox に空の選択要素が異なる色で表示されています。問題は、ユーザーが色を選択したときに、JComboBox で選択した色が変わらないことです。ユーザーがリストから色を選択したときに、その色が JComboBox フィールドに表示されるようにするには、どのコード行をどこに追加すればよいですか?

私はいくつかの解決策を試しましたが、結果は、ユーザーが JComboBox で色の選択を選択すると、常に灰色に変わるということでした...

私はいくつかの同様の質問に目を通しましたが、選択が完了したときにコードのどの部分が JComboBox の色の変更を扱っているのかわかりません...

4

3 に答える 3

0

index == -1 のケースを追加し、セル レンダラーの背景色を最新のユーザー選択に設定します。

于 2013-09-16T15:04:20.610 に答える