我想在点击按钮时隐藏所选面板。我有大部分工作,但当一个面板是假不会更新。
这是我尝试过的一件事:
compsToExperiment.setVisible(mapVis);
updateUI();
private void updateUI() {
SwingUtilities.updateComponentTreeUI(this);
}
这是在正确的轨道上? 其他任何方式吗?
答案 0 :(得分:2)
updateComponentTreeUI()
不会强行重绘。您必须使用repaint
方法。
compsToExperiment.setVisible(mapVis);
frame.repaint();
其中frame
是面板所在的顶部窗口。
答案 1 :(得分:2)
除了在setVisible(false);
上调用JPanel
之外,您不必做任何花哨的事情。下面的例子证明了这一点:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InvisiblePanel
{
private JPanel centerPanel;
private JPanel footerPanel;
private JTextField addField;
private JTextField nameField;
private JTextField occField;
private JTextField phoneField;
private JLabel nameLabel;
private JLabel addLabel;
private JLabel occLabel;
private JLabel phoneLabel;
private JPanel contentPane;
private JButton hideButton;
private void displayGUI()
{
JFrame frame = new JFrame("Invisible Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setBackground(Color.RED.darker().darker());
contentPane.setLayout(new BorderLayout(5, 5));
nameLabel = new JLabel("Guarantee Name : ");
nameField = new JTextField();
addLabel = new JLabel("Address : ");
addField = new JTextField();
occLabel = new JLabel("Occupation : ");
occField = new JTextField();
phoneLabel = new JLabel("Phone : ");
phoneField = new JTextField();
centerPanel = new JPanel();
hideButton = new JButton("Hide");
hideButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
if (centerPanel.isShowing())
centerPanel.setVisible(false);
else
centerPanel.setVisible(true);
}
});
centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setLayout(new GridLayout(0, 2, 5, 5));
centerPanel.add(nameLabel);
centerPanel.add(nameField);
centerPanel.add(addLabel);
centerPanel.add(addField);
centerPanel.add(occLabel);
centerPanel.add(occField);
centerPanel.add(phoneLabel);
centerPanel.add(phoneField);
footerPanel = new JPanel();
footerPanel.add(hideButton);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new InvisiblePanel().displayGUI();
}
});
}
}
答案 2 :(得分:1)
您可以执行JFrame.invalidate()进行刷新。有关详细信息,请查看链接。对不同问题的类似要求。 refresh the contents of frame in real time