简体   繁体   中英

hide options in comboBox java swing

I'm wanting to create the option for users in a game to select their own piece to play with from a list of piece's that I have made. To do this I have two comboBox's that contain the same items in them but i dont want users to be able to select the same piece.

I have thought about removing the item from comboBox 1 if selected in comboBox2 (and adding it back later) but i am using the index of the selected item later when i assign the image to the 'player' class and so this would get messy there and also the indexing of each list would be different since they dont contain the item that the other has selected (hope that makes sense).

How can i make the item in comboBox 2 hidden or unselectable if it is selected in comboBox 1?

Many thanks

Create POJO which represents the basic properties of the Piece ...

public class Piece {

    private Image image;
    private String name;

    public Piece(String name, Image image) {
        this.image = image;
        this.name = name;
    }

    public Image getImage() {
        return image;
    }

    public String getName() {
        return name;
    }

}

Add these to your JComboBox

Piece[] pieces = new Piece[]{
    // Create what ever pieces you need...
}
DefaultComboBoxModel modelPlayer1 = new DefaultComboBoxModel(pieces);
DefaultComboBoxModel modelPlayer2 = new DefaultComboBoxModel(pieces);

JComboBox cbPlayer1 = new JComboBox(modelPlayer1);
JComboBox cbPlayer2 = new JComboBox(modelPlayer2);

You will find that you will probably need a ListCellRenderer of some kind in order to display the name of the Piece in the JComboBox , for example...

public class PieceListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        if (value instanceof Piece) {
            value = ((Piece)value).getName();
        }
        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    }

}

Then apply the renderer to the comboboxes

cbPlayer1.setRenderer(new PieceListCellRenderer());
cbPlayer2.setRenderer(new PieceListCellRenderer());

Now, you don't need to care about the indecies, and because you've built the two models from the same array of Pieces you should have no issue simply removing them by reference...

Piece p = (Piece)cbPlayer1.getSelectedItem();
((DefaultComboBoxModel)cbPlayer2.getModel()).removeElement(p);

See How to Use Combo Boxes for more details

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