JComboBox更改下拉箭头图像不起作用

问题描述 投票:4回答:1

我正在尝试使用自定义图像更改JComboBox的下拉箭头,但该代码似乎无法正常工作。我遵循了here的指示。我尝试同时使用Java 1.8.131和AdoptOpenJDK 11.0.5,但两者的结果相同。在下面,您可以找到我正在使用的完整代码:

Main.java

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { 
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    JFrame f = new JFrame("Window");
    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 400, 400);
    panel.setBackground(Color.gray);

    JComboBox<String> box = new JComboBox<>();//simple JComboBox with custom UI
    box.setPreferredSize(new Dimension(150, 30));
    box.setUI(MyBasicComboboxUI.createUI(box));

    box.addItem("BasicComboBoxUI1");
    box.addItem("BasicComboBoxUI2");
    box.addItem("BasicComboBoxUI3");

    panel.add(box);

    JButton btn = new JButton("SimpleJButton");//simple JButton with an image on it (to prove that the image loads)
    btn.setPreferredSize(new Dimension(120, 30));
    MyImageProvider imageProvider = new MyImageProvider();
    btn.setIcon(new ImageIcon(imageProvider.getImage()));
    btn.setBorder(new EmptyBorder(0, 0, 0, 0));

    panel.add(btn);
    f.add(panel);
    f.setSize(400, 400);
    f.setLayout(null);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}

MyBasicComboboxUI.java:

public class MyBasicComboboxUI extends BasicComboBoxUI {
    public static ComboBoxUI createUI(JComponent c) {
        return new MyBasicComboboxUI();
    }

    @Override
    protected JButton createArrowButton() {
        JButton arrowButton = super.createArrowButton();
        MyImageProvider imgProvider = new MyImageProvider();
        arrowButton.setSize(new Dimension(40, 40));
        arrowButton.setToolTipText("My tooltip");
        arrowButton.setIcon(new ImageIcon(imgProvider.getImage()));//set the same icon here
        arrowButton.setBorder(new EmptyBorder(0, 0, 0, 0));
        return arrowButton;
    }
}

MyImageProvider.java

public class MyImageProvider {

    public Image getImage() {
        try {
            Image img = ImageIO.read(getClass().getResource("/icons/arrow.gif"));
            return img;
        } catch (IOException e) {
            System.out.println("The image was not loaded.");
        }
        return null;
    }
}

使用的图像12px x 12px:arrow.gif

[24px x 24px的图片:enter image description here

运行程序时的输出:

enter image description here

在箭头上设置的工具提示正在起作用。如果使用自定义背景色,则相同。但如果我设置图像,则不会。我尝试使用:* .jpg,*。gif,*。png和其他分辨率:16x16、14x14、12x12、8x8等,但均未成功。在所有情况下,图像仅加载在SimpleJButton上,而不加载在组合框的下拉箭头按钮上。

Eclipse结构:

enter image description here

java swing jcombobox
1个回答
3
投票

您的问题是线路

JButton arrowButton = super.createArrowButton();

您应该将其更改为

JButton arrowButton = new JButton();

背景:super.createArrowButton()返回ArrowButton类的实例,该类提供自定义箭头绘制,但不支持setIcon方法。

© www.soinside.com 2019 - 2024. All rights reserved.