0

Есть переопределенный JComboBox, в котором вставлены свои иконки. Код скопирован и до конца не понятен. Проблема в том, что текст(названия позиций) отображается только при нажатии на кнопку со стрелкой, при нажатии на поле списка, список выпадает с иконками но без текста, в неактивном состоянии текст тоже не отображается. Помогите, подскажите.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import java.net.URL;


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.ListCellRenderer;
import javax.swing.UIManager;






public class testL extends JFrame {
Dimension d=new Dimension(500, 500);
JPanel windowContent= new JPanel();
JComboBox fromComboBox;

public testL() {
    setPreferredSize(d);
    setLayout(new BorderLayout());
    windowContent.setLayout(null);
    setContentPane(windowContent);


    selectLng();
    fromComboBox.setBounds(0,0,100,25);
    windowContent.add(fromComboBox);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);


}


void selectLng(){
    String[] items = { "ENG", "UKR", "RU" };
    int sizeBox = items.length;

    ImageIcon[] image = new ImageIcon[sizeBox];

    image[0] = new ImageIcon("images/eng.png");
    image[1] = new ImageIcon("images/ukr.png");
    image[2] = new ImageIcon("images/ru.png");

         Integer[] intArray = new Integer[sizeBox];
            for (int i = 0; i<sizeBox; i++){
                intArray[i] = new Integer(i);
            }
            fromComboBox = new JComboBox(intArray);
            fromComboBox.setRenderer(new ComboBoxRender(image, items));


}

 protected static ImageIcon createIcon(String path) {
        URL imgURL = testL.class.getResource(path);    
        if (imgURL != null) {
            System.out.println(imgURL);
            return new ImageIcon(imgURL);
        } else {
            System.err.println("File not found " + path);
            return null;
        }
 }

 public class ComboBoxRender extends JLabel implements ListCellRenderer{

        private ImageIcon[] icon;
        private String[] textBox;
        public ComboBoxRender(ImageIcon[] icon, String[] textBox){
            this.icon = icon;
            this.textBox = textBox;
        }

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
            int selecIndex = ((Integer)value).intValue();
            setIcon(icon[selecIndex]);
            setText(textBox[selecIndex]);
            return this;
        }
  }

public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {}
    javax.swing.SwingUtilities.invokeLater(
            new Runnable() {public void run() {
                new testL();
                }
            }
        );
}
}

1 ответ 1

0

Добавленные строчки : в классе ComboBoxRender переопределяем сеттеры граундов

        @Override
        public void setBackground(Color bg) {
            super.setBackground(Color.WHITE);
        }
        @Override
        public void setForeground(Color fg) {
            super.setBackground(Color.BLACK);
        } 

полный код

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.net.URL;
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.ListCellRenderer;
import javax.swing.UIManager;






public class testL extends JFrame {
Dimension d=new Dimension(500, 500);
JPanel windowContent= new JPanel();
JComboBox fromComboBox;
JPanel lng= new JPanel();


public testL() {
    setPreferredSize(d);
    setLayout(new BorderLayout());
    windowContent.setLayout(null);
    setContentPane(windowContent);

    selectLng();

    fromComboBox.setBounds(0,0,150,50);
    windowContent.add(fromComboBox);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);


}


void selectLng(){
    String[] items = { "ENG", "UKR", "RU" };
    int sizeBox = items.length;

    ImageIcon[] image = new ImageIcon[sizeBox];

    image[0] = new ImageIcon("images/eng.png");
    image[1] = new ImageIcon("images/ukr.png");
    image[2] = new ImageIcon("images/ru.png");

         Integer[] intArray = new Integer[sizeBox];
            for (int i = 0; i<sizeBox; i++){
                intArray[i] = new Integer(i);
            }
           fromComboBox = new JComboBox(intArray);
           fromComboBox.setRenderer(new ComboBoxRender(image,items));
}

 protected static ImageIcon createIcon(String path) {
        URL imgURL = testL.class.getResource(path);    
        if (imgURL != null) {
            System.out.println(imgURL);
            return new ImageIcon(imgURL);
        } else {
            System.err.println("File not found " + path);
            return null;
        }
 }

 public class ComboBoxRender extends JLabel implements ListCellRenderer{

        private ImageIcon[] icon;
        private String[] textBox;

        public ComboBoxRender(ImageIcon[] icon, String[] textBox){
            this.icon = icon;
            this.textBox = textBox;
        }

        //НАДО БЫЛО ПЕРЕОПРЕДЕЛИТЬ СЕТЕРЫ БЭК И ФОРГРАУНДОВ
        @Override
        public void setBackground(Color bg) {
            super.setBackground(Color.WHITE);
        }
        @Override
        public void setForeground(Color fg) {
            super.setBackground(Color.BLACK);
        }//КОНЕЦ ДОБАВЛЕНОГО ПЕРЕОПРЕДЕЛЕНИЯ

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
            int selecIndex = ((Integer)value).intValue();
            setIcon(icon[selecIndex]);
            setText(textBox[selecIndex]);

            return this;
        }
    }



public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {}

    javax.swing.SwingUtilities.invokeLater(
            new Runnable() {public void run() {
                new testL();
                }
            }
        );
}
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.