使JComboBox透明化

时间:2012-12-18 18:27:29

标签: java swing jcombobox

我在使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 个答案:

答案 0 :(得分: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;
    }});

答案 1 :(得分: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

答案 2 :(得分:-1)

您需要预设这几件事

jcombo.setOpaque(false);
jcombo.setContentAreaFilled(false);
jcombo.setBorderPainted(false);

答案 3 :(得分:-1)

试试这个。

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

setUI(new BasicComboBoxUI() {

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

   }
});