0

What I am trying to do is to create a JLabel dependent of the selection in the combo box, i.e. if "History Book" is selected create a label "Enter period", if "Fictional Book" is selected create label "Enter genre". The thing is no matter what I select the Label is not visible, the place it should be stays empty. Any ideas where I am wrong ?

Here is my code:

JComboBox comboBox = new JComboBox(bookTypes);
    comboBox.setModel(new DefaultComboBoxModel(new String[] {"History Book", "Fictional Book", "Textbook"}));
    comboBox.setToolTipText("Choose the type of book here!");
    comboBox.setBounds(196, 48, 156, 20);
    ActionListener cbActionListener = new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            String s = (String) comboBox.getSelectedItem();
            if(s.equals("History Book")){
                JLabel lblWriteThePeriod = new JLabel("Write the Period:");
                lblWriteThePeriod.setBounds(10, 317, 142, 14);
                dialog.getContentPane().add(lblWriteThePeriod);
            }else if(s.equals("Fictional Book")){
                JLabel lblWriteTheGenre = new JLabel("Write the genre:");
                lblWriteTheGenre.setBounds(10, 317, 142, 14);
                dialog.getContentPane().add(lblWriteTheGenre);
            }
        }           
    };
    comboBox.addActionListener(cbActionListener);
    dialog.getContentPane().add(comboBox);
dialog.setVisible(true);
Phantomazi
  • 408
  • 6
  • 22
  • 1
    1) Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). .. – Andrew Thompson Dec 14 '14 at 02:58
  • .. 3) Create the label at application start-up, then call `setText(..)` when it should become visible. – Andrew Thompson Dec 14 '14 at 02:58
  • Thank you for all of the guidance ! It is working now. – Phantomazi Dec 14 '14 at 03:48
  • You're welcome. Glad you got it sorted! :) Now you might a) delete the question or (better) b) provide your own answer (as an answer - look below for the 'Answer your own question' button). – Andrew Thompson Dec 14 '14 at 04:43

0 Answers0