Search code examples
javaswingjbutton

When I click my JButton, the JLabel doesn't show on the window,


I tried to make a JButton that would put a JLabel in the window, but when I click the button, it doesn't seem to put the JLabel in the window. The button seems to work when I use it for the console, but not for putting the JLabel in the window. Why is this, and what should I do?

Here's my code:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class AnimaleseTranslator implements ActionListener {
    
    private static JPanel panel;
    private static JLabel label;
    
    public AnimaleseTranslator() {
        
        JFrame frame = new JFrame();
        
        panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(220, 391, 220, 391));
        panel.setLayout(new GridLayout(0, 1));
        
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null); // centers the JFrame
        frame.setTitle("Animalese Translator");
        frame.setVisible(true);
        
        JButton button = new JButton("Click me!");
        button.setBounds(100, 100, 98, 55);
        button.addActionListener(this);
        panel.add(button);
        
        label = new JLabel("lkdsajflksdjlaskdjf");
        label.setBounds(200, 200, 50, 50);
        
    }
    
    public static void main(String[] args) {
        new AnimaleseTranslator();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        panel.add(label);
    }

}

Solution

  • but when I click the button, it doesn't seem to put the JLabel in the window.

    1. The setBounds(...) statement does nothing. Swing uses layout managers by default and the layout manager will set the size/location of each component. So get rid of the setBounds() statement because it is confusing.
    2. Components need to be added to the frame BEFORE the frame is made visible. The pack() or setVisible() statement will then invoke the layout manager.
    3. After you add a component to panel on a visible frame you need to invoke panel.revalidate() to invoke the layout manager. So you need to add the revalidate() in the ActionListener.
    4. Get rid of the setBorder(...) statement until you better understand what it does. The problem with your current code is the border is too big, so there is no room for the button and label to display properly.