-1

In my application I have a list of 6 Jlabels, which are added to the contentPane in a for loop. After that I add 2 JButtons - one for removing all the labels and the second one for adding them again:

public class Test {

    private JFrame frame;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test window = new Test();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Test() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 960, 620);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.getContentPane().setLayout(null);
        frame.getContentPane().setBackground(new Color(30, 30, 30));


        LinkedList<JLabel> labels = new LinkedList<>();
        for(int i = 0 ; i < 6 ; i++) {
            labels.get(i).setSize(280, 50);
            labels.setBackground(new Color(75, 75, 75));
            labels.setOpaque(true);
        }

        Button buttonAdd = new JButton("Add");
        buttonAdd.setBounds(310, 15, 150, 50);
        buttonAdd.addMouseListener(new MouseAdapter() {
            @Override
            public final void mouseClicked(MouseEvent event) {
                for(int i = 0 ; i < 6 ; i++) {
                    labels.get(i).setLocation(15, 15+50*i);
                    frame.getContentPane().add(labels.get(i));
                }
            }
        });

        Button buttonRemove = new JButton("Remove");
        buttonRemove.setBounds(310, 15, 150, 50);
        buttonRemove.addMouseListener(new MouseAdapter() {
            @Override
            public final void mouseClicked(MouseEvent event) {
                for(int i = 0 ; i < 6 ; i++) {
                    frame.getContentPane().remove(labels.get(i));
                }
            }
        });
    }
}

When I added the 6 labels outside of linsteners they were properly added to the ContentPane and displayed. Yet, when I try to do this via the buttons, upon clicking the buttonAdd nothing happens. They do not get displayed.

I tried messing with the hierarchy, setting the indices manually but nothing worked. I suspect the MouseListeners but I have no idea why this doesn't work.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Virginia
  • 41
  • 6
  • Is the listener working? Does it print something to the console using sysout? Try this: https://alvinalexander.com/java/jbutton-listener-pressed-actionlistener – Marvin Klar Nov 20 '18 at 22:36
  • Yes, I have tried printing out something like `System.out.println("foo");` and it did show `foo` in the console. – Virginia Nov 20 '18 at 22:42
  • But you called 'remove' instead of 'add' :D didn't saw this first. – Marvin Klar Nov 20 '18 at 22:44
  • little typo, it still doesn't work though :( – Virginia Nov 20 '18 at 22:47
  • Try calling the https://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#validate() function after adding the components – Marvin Klar Nov 20 '18 at 22:52
  • 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. 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) What do the 6 labels represent? It's likely there is a better approach to this, but impossible to know what, without more details. – Andrew Thompson Nov 20 '18 at 23:13
  • 1
    (1-) 1) The code you posted doesn't compile. Post actual code that you are testing. We don't have time to guess what you really are testing. 2) You should be adding an `ActionListener` to the button, not a MouseListener. – camickr Nov 21 '18 at 00:29

1 Answers1

1

First things first;

-Anything modifies the GUI has to be done in Event Dispatch Thread(EDT). You can read more why it is needed from this answer.


You have to call:

 Test.this.frame.revalidate();
 Test.this.frame.repaint();

Like below:

           for ( int i = 0; i < 6; i++ )
           {
              final JLabel l = labels.get( i );
                              l.setLocation( 15, 15 + (50 * i) );
              Test.this.frame.getContentPane().add( l );
           }
           Test.this.frame.revalidate();
           Test.this.frame.repaint();

Asides this I see in your code you use Button instead of JButton, I am assuming it is just a typing mistake. It should be JButton. Also

    for(int i = 0 ; i < 6 ; i++) {
    labels.get(i).setSize(280, 50);
    labels.setBackground(new Color(75, 75, 75));
    labels.setOpaque(true);
    }

this piece of code is just wrong, labels is a list not a JLabel. Define local variable

JLabel labelToAdd = labels.get(i)
labelToAdd.setSize(280, 50);
labelToAdd.setBackground(new Color(75, 75, 75));
labelToAdd.setOpaque(true);
Bleach
  • 309
  • 3
  • 18
  • 1
    `Anything modifies the GUI has to be done in Event Dispatch Thread(EDT).` - correct, but code executed from within a listener does execute on the EDT, so there is no need to use the invokeLater(). – camickr Nov 21 '18 at 00:21