-1

I have some labels in my code that I don't want shown until a button is pressed. I put .setVisable(false) on all the labels and in the action listener for the button, put .setVisable(true) on all the labels. When I run the program and press the button, the labels do not appear.

Here is one of the labels

try{
        lblPressure2 = new JLabel(toolKit.getPressure(selectedTown.toLowerCase()));
        lblPressure2.setBounds(322, 114, 61, 14);
        lblPressure2.setVisible(false);
        panel.add(lblPressure2);
        }catch(Exception e){e.printStackTrace();}

and here is my button

btnGet = new JButton("Show Me The Weather");
        btnGet.setBounds(119, 71, 176, 24);
        innerP.add(btnGet);
        btnGet.addActionListener
        (new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                lblPressure2.setVisible(true);

            }
        });
Craig
  • 364
  • 1
  • 3
  • 25
  • 1) Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/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 Jan 26 '15 at 01:22
  • .. 3) 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). – Andrew Thompson Jan 26 '15 at 01:23
  • There are a number possible issues. To start with, when not visible components are not consider when calculating the layout requirements. Thus means that when made visible, you need to recalculate the layout requirements, the simplest way is to call revalidate on the container. The problem is, the container may longer fit within its parent or frame ... – MadProgrammer Jan 26 '15 at 01:46

2 Answers2

1

It's unclear what you're using as the parent component to draw on, but i'll assume it is 'panel'. The view is not being updated so you need to call repaint() on the parent component, this will in turn call paint on all it's child components.

btnGet.addActionListener
    (new ActionListener () {
        public void actionPerformed(ActionEvent e) {
            lblPressure2.setVisible(true);
            panel.repaint();
        }
    });
1

Instead of using .setVisible(true) in the action listener. I made the labels content blank and used .setText in the action listener and it worked.

Craig
  • 364
  • 1
  • 3
  • 25