简体   繁体   中英

Add JList Items based on JComboBox selection

When I click on a JComboBox item, I want it to display sentences in two different Jlists:

crosswordCategories = new JComboBox();

    crosswordCategories.addItem("Animals");
    crosswordCategories.addItem("Roman Empire");
    crosswordCategories.addItem("Geography");
    Object comboSelected = crosswordCategories.getSelectedItem();


    horizList = new JList();  
    horizList.setBounds(35, 430, 420, 170);
    horizList.setBackground(Color.white);
    horizList.setBorder(BorderFactory.createEtchedBorder(1));
    add(horizList);


    vertList = new JList();  
    vertList.setBounds(490, 430, 420, 170);
    vertList.setBackground(Color.white);
    vertList.setBorder(BorderFactory.createEtchedBorder(1));
    add(vertList);

If I click on the "Animals" category, it should display on the Horizontal JList "Big animal, with big ears and long nose." and on the Vertical JList "Man's best Friend.", just to put an example.

How do I do this? *It is for a crossword puzzle btw.

Edit: when the App starts, the JLists are empty.

  • You need some way to associate the values in the JComboBox with the values you want to display, something kind a Map might do, but I'd prefer to use a POJO personally. See Collections Trail for more details
  • You need to know when the JComboBox selection changes. Something like an ActionListener would probably do. See How to Use Actions and How to Use Combo Boxes for more details
  • Once the selection has changed, you need to get the selected item from the combo box ( getSelectedItem ), use the associated Map to look up the value and probably use JList#addItem to add the value to the JList , assuming you don't want to remove the existing items, otherwise, it would be quicker to just replace the JList 's model. See How to Use Lists for more details.

You may also want to take a look at How to Use Scroll Panes

You should also avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

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