java - 如何让 JLabel 在不可见时占用空间?

网上365体育买球波胆提现 2025-09-07 00:44:39 admin

我有一个程序可以创建 2 个面板,然后在其中放置一个标签和两个按钮。标签设置为不可见setVisible(false),然后添加两个按钮并打包框架。当我单击第一个按钮时,显示标签,,第二setVisible(true)个按钮再次隐藏它,setVisible(false)。当我单击每个按钮时,它们会移动以在标签隐藏时填充标签的空间,然后再次移动以避开显示的标签。我想阻止这种情况发生,即使标签被隐藏也让按钮保持在同一个地方。

这是代码:

public class MainFrame extends JFrame{

public JLabel statusLabel;

public JButton show;

public JButton hide;

public MainFrame(){

super("MagicLabel");

JPanel topPanel = new JPanel(); //Create Top Panel

statusLabel = new JLabel(""); //Init label

statusLabel.setVisible(false); //Hide label at startup

topPanel.setSize(400, 150); //Set the size of the panel, Doesn't work

topPanel.add(statusLabel); //Add label to panel

JPanel middlePanel = new JPanel(); //Create Middle Panel

show= new JButton("Show"); //Create show button

hide= new JButton("Hide"); //Create hide button

middlePanel.setSize(400, 50); //Set the size of the panel, Doesn't work

middlePanel.add(show); //Add show button

middlePanel.add(hide); //Add hide button

this.add(topPanel, "North"); //Add Top Panel to North

this.add(middlePanel, "Center"); //Add Middle Panel to Center

addActionListeners(); //void:adds action listeners to buttons

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setBounds(100, 100, 512, 400);

this.setPreferredSize(new Dimension(400,200)); //Set size of frame, Does work

this.pack();

this.setVisible(true);

}

public void animateInstall(boolean var0){ //Void to show and hide label from action listeners

statusLabel.setVisible(var0);

sendWorkingMessage("Boo!");

}

public void sendWorkingMessage(String message){ //Void to set text of label

this.statusLabel.setForeground(new Color(225, 225, 0));

this.statusLabel.setText(message);

}

void addActionListeners(){

show.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

animateInstall(true);

}

});

hide.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

animateInstall(false);

}

});

}