2

我在使 JComboBox 透明时遇到问题。我尝试将 opaque 设置为 false 和背景 0 的 alpha,但它不起作用。我想我需要更改一些进行渲染或类似操作的类。这是代码..

  import java.awt.EventQueue;
  import java.awt.Graphics;
  import java.awt.Rectangle;

  import javax.swing.JFrame;
  import javax.swing.JComboBox;
  import javax.swing.JTextField;
  import javax.swing.plaf.basic.BasicComboBoxUI;

  import java.awt.Color;


public class App {

private JFrame frame;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                App window = new App();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public App() {
    initialize();
}

private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setBackground(Color.GREEN);
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
    JComboBox comboBox = new JComboBox(petStrings);
    comboBox.setBounds(149, 99, 155, 20);
    comboBox.setOpaque(false);
    //comboBox.setBackground(new Color(0,0,0,0));
    ((JTextField)comboBox.getEditor().getEditorComponent()).setOpaque(false);
    comboBox.setUI(new BasicComboBoxUI(){  

        public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus){}});  
    frame.getContentPane().add(comboBox);

}

}
4

4 回答 4

2

假设您只希望 ComboBox 的文本字段透明(也不是弹出窗口),使用以下代码应该可以工作。您需要弄乱 ComboBox 渲染器而不是编辑器。如果您可以在 ComboBox 中键入,则使用编辑器;如果 ComboBox 只是一个值列表,则使用渲染器。

comboBox.setOpaque(false);
comboBox.setRenderer(new DefaultListCellRenderer(){
    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        JComponent result = (JComponent)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        result.setOpaque(false);
        return result;
    }});
于 2012-12-18T20:50:19.333 回答
1
JComboBox myComboBox = new JComboBox(array);
myComboBox .setOpaque(false);
myComboBox .setEditable(true);
JTextField boxField = (JTextField)myComboBox .getEditor().getEditorComponent();
boxField.setBorder(BorderFactory.createEmptyBorder());
boxField.setBackground(new Color(0, 0, 0, 0));
boxField.setFocusable(false);

答案在http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6687960

于 2016-04-26T03:14:18.030 回答
-1

尝试这个。

yourComboBox.setOpaque(false);
((JTextField)yourComboBox.getEditor().getEditorComponent()).setOpaque(false);

setUI(new BasicComboBoxUI() {

   @Override    
   public void paintCurrentValueBackground(
       Graphics g, Rectangle bounds, boolean hasFocus) {

   }
});
于 2013-11-06T13:51:04.183 回答
-1

你需要预设这几件事

jcombo.setOpaque(false);
jcombo.setContentAreaFilled(false);
jcombo.setBorderPainted(false);
于 2012-12-18T18:30:59.920 回答