简体   繁体   中英

Java remove JComboBox arrow button

I added a JComboBox from the palette using netbeans IDE and populated it with contents from mysql database. I also added autocomplete functionality using swingx-all-1.6.5-1

method for populating combobox

    public void doPopulateCombo(){
    Connection con = Functions.ConnectToDB();
    try {
        Statement stmt = con.createStatement();
        String sqlQuery = "select * from products";
        ResultSet rs = stmt.executeQuery(sqlQuery);

        while(rs.next()){
            String product_name = rs.getString("Product_Name");
            cboProducts.addItem(product_name);
        }
        con.close();
        cboProducts.setSelectedIndex(-1);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Error populating combo box\n"+e.toString(),
                "Error",JOptionPane.ERROR_MESSAGE);
    }
}

How do I remove the combobox's arrow button so that it appears like a textbox?

The best I can come up with is putting it into a JPanel that's slightly smaller than it, but depending on the L&F that's not really the best way to do it. Alternatively you could make a class that extends JComboBox, overrides the paint(Graphics g) method and from there calls the paint method of a textbox with the same dimensions. At least, I think you could do that, if you wanted to. Do note that you'd have to update what's in the textbox each time the user selects an option.

A hacky way to fix this would be to create your own implementation of BasicComboBoxUI and override createArrowButton()

public class NoArrowJComboBoxUI extends BasicComboBoxUI {

    @Override
    protected JButton createArrowButton() {
        JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(0,0));
        btn.setVisible(false);
        return btn;
    }

}

Then in your existing code:

    cboProducts.setSelectedIndex(-1);
    cboProducts.setUI(new NoArrowJComboBoxUI());

This implementation should not interfere with autocomplete behavior, however, I haven't tested it myself with autocomplete so I can't say that with certainty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM