Sha*_*anu 1 java swing resize jpanel jframe
我有一个程序,我有JFrame一个JButton在其中.当用户单击时JButton,将删除所有Components内容JFrame,并向其JPanel添加带红色背景的内容.
当我点击时JButton,JPanel除非我调整大小JFrame(我使用的是Windows 7),否则该红色不会显示.有没有办法实现我想要的,而无需手动调整大小JFrame?
这是我正在使用的代码的一部分:
public class Demo implements ActionListener{
public static void main(String args[]){
...............
button.addActionListener(this); //'button' is an object of Jbutton class.
frame.setVisible(true); //'frame' is an object of JFrame class.
............
}
public void actionPerformed(ActionEvent ae){
frame.removeAllComponents();
frame.add(panel1); //panel1 is an object of Jpanel class with red background.
/* Here is where my problem lies.
panel1 is not visible to me unless I manually resize the JFrame. */
}
}
Run Code Online (Sandbox Code Playgroud)
要从JPanel或从必须调用的顶级容器中删除(然后,例如,添加新的JComponents)JComponents,只需执行一次并在操作结束时:
revalidate();
repaint();
Run Code Online (Sandbox Code Playgroud)
如果您只调整大小或更改JComponents:
validate();
repaint();
Run Code Online (Sandbox Code Playgroud)
对我来说,这有点奇怪。事实证明,调用remove(Component comp)、添加 new JPanel,然后调用pack()对我有用。
public class Demo{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
final JButton button = new JButton("Press Me");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
frame.remove(panel);
final JPanel redPanel = new JPanel(){
@Override
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.setColor(Color.RED);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
frame.add(redPanel);
frame.pack();
}
});
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
按下按钮之前

按下按钮后

怪事
removeAll()实际上导致 GUI 冻结。这个事件以前好像发生过也发生过这样的事情。即使我尝试在删除所有组件之前删除操作侦听器,也会发生这种情况。