当我单击我的 JButton 时,JLabel 没有显示在 window 上,

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

我试图制作一个 JButtonJLabel 放入 window,但是当我单击该按钮时,它似乎没有将 [=13] =] 在 window 中。当我将它用于控制台时,该按钮似乎有效,但不适用于将 JLabel 放入 window。这是为什么,我该怎么办?

这是我的代码:

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);
    }

}

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

  1. setBounds(...) 语句不执行任何操作。 Swing默认使用布局管理器,布局管理器会设置每个组件的size/location。所以去掉 setBounds() 语句,因为它令人困惑。
  2. 在框架可见之前,需要将组件添加到框架中。然后 pack() 或 setVisible() 语句将调用布局管理器。
  3. 将组件添加到可见框架上的面板后,您需要调用 panel.revalidate() 来调用布局管理器。所以你需要在ActionListener中添加revalidate()
  4. 删除 setBorder(...) 语句,直到您更好地理解它的作用。您当前代码的问题是边框太大,因此按钮和标签无法正常显示。