import javax.swing.*;
import java.awt.*;
public class yumen
{
public static void main(String args[])
{
ImageIcon iconF= new ImageIcon("bj004.jpg");
JLabel jlabelF= new JLabel("登录中。",iconF,JLabel.CENTER);
jlabelF.setHorizontalTextPosition(JLabel.CENTER);
jlabelF.setVerticalTextPosition(JLabel.CENTER);
jlabelF.setForeground(Color.green);
ImageIcon iconS = new ImageIcon("bj009.gif");
JLabel jlabelS = new JLabel(iconS);
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(600,500);
app.setLocationRelativeTo(null);//居中
app.getContentPane().add(jlabelS);
app.setVisible(true);
app.removeAll();
app.setLayout(new FlowLayout());
app.setSize(300,300);
app.add(jlabelF);
// app.doLayout();
app.validate();
app.setVisible(true);
}}
再调用removeAll()后,重新加组件却显示不出来,validate()也不知道用的对不对,无语了,高手来解决下呗
import java.awt.*;
public class yumen
{
public static void main(String args[])
{
ImageIcon iconF= new ImageIcon("bj004.jpg");
JLabel jlabelF= new JLabel("登录中。",iconF,JLabel.CENTER);
jlabelF.setHorizontalTextPosition(JLabel.CENTER);
jlabelF.setVerticalTextPosition(JLabel.CENTER);
jlabelF.setForeground(Color.green);
ImageIcon iconS = new ImageIcon("bj009.gif");
JLabel jlabelS = new JLabel(iconS);
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(600,500);
app.setLocationRelativeTo(null);//居中
app.getContentPane().add(jlabelS);
app.setVisible(true);
app.removeAll();
app.setLayout(new FlowLayout());
app.setSize(300,300);
app.add(jlabelF);
// app.doLayout();
app.validate();
app.setVisible(true);
}}
再调用removeAll()后,重新加组件却显示不出来,validate()也不知道用的对不对,无语了,高手来解决下呗
不要app.removeAll();
这个是重要的忘记跟你提了。你带有居中注释的那行语句结束的分号是全角的,不对。app.add(jlabelF);最好如同你前面的那样,app.getContentPane().add(jlabelS);虽然它们其实一样。
一般会在后面调用一下validate();如果是子类可以调用revalidate();
JLabel jlabelF = new JLabel("登录中。", iconF, JLabel.CENTER);
jlabelF.setHorizontalTextPosition(JLabel.CENTER);
jlabelF.setVerticalTextPosition(JLabel.CENTER);
jlabelF.setForeground(Color.green);
ImageIcon iconS = new ImageIcon("bj009.gif");
JLabel jlabelS = new JLabel(iconS); JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(600, 500);
app.setLocationRelativeTo(null);// 居中
app.getContentPane().add(jlabelS);
app.setVisible(true); app.getContentPane().removeAll(); app.setLayout(new FlowLayout());
app.setSize(300, 300);
app.add(jlabelF);
// app.doLayout();
// app.getContentPane().validate();
// app.setVisible(true);
请运行以上代码。确认是否符合你的预想。
我想问用app.removeAll()为啥不好使呢,可否指教下
人家平常都是向contentpane上添加组件,这回再添加,你让人家怎么玩啊?contentpane没有了。这会导致一系列的问题。
看一下源码中JFrame的addImpl方法:
protected void addImpl(Component comp, Object constraints, int index)
{
if(isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}这个super是container。那paintComponents方法的时候,也就是绘制组件的时候会出问题。
具体什么问题哦,我就没跟那么深入了。如果你知道了,记得告诉我。
app.setVisible(true);
这样可以,不过,个人觉得这种方法不好