Reputation: 43
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);
}
}
Upvotes: 0
Views: 350
Reputation: 324118
but when I click the button, it doesn't seem to put the JLabel in the window.
panel.revalidate()
to invoke the layout manager. So you need to add the revalidate()
in the ActionListener.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.Upvotes: 3