import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class wt126 extends JFrame implements ActionListener
{
JProgressBar pb;
Timer tm;
int i=0;
wt126()
{
super("时钟");
setVisible(true);
setSize(200,100);
setLayout(new GridLayout(2,1));
Container cp=getContentPane();
pb=new JProgressBar(0,100);
pb.setBackground(Color.yellow);
pb.setForeground(Color.blue);
pb.setStringPainted(true);
JPanel pn=new JPanel();pn.setLayout(new FlowLayout());
pn.add(pb);
JLabel lb=new JLabel("下载完自动关闭对话框",JLabel.CENTER);
cp.add(pn);cp.add(lb);
tm=new Timer(200,this);
tm.start();
}
public void actionPerformed(ActionEvent e)
{
i=i+1;
pb.setValue(i);
pb.setString("已下载"+i+"%");
if(i>=100)
{
pb.setString("已下载完毕"+"\n");
tm.stop();
System.exit(0);
}
}
public static void main(String args[])
{
wt126 frm=new wt126();
}
}
我在JCreater上运行完后,在编译时cmd中出现:
Exception in thread"main"java.lang.Error:Do not wt126.setLayout<> use wt126.getContentPane<>.setLayout<> instead
at javax.swing.JFrame.createRootPaneException<JFrame.java:465>
at javax.swing.JFrame.setLayout<JFrame.java:531>
at wt126.<init><wt126.java:14>
at wt126.main<wt126.java:41>
虽然可以运行,但是里面少了百分比滑动的滚动条和那行字。
------解决方案--------------------------------------------------------
你用的是哪个版本的jdk?
最初 需要先获取内容窗格contentPane。应该是从1.5开始,为了简化这一步可以跳过。
1.4
Container container = frame.getContentPane();
container.setLayout(new GridLayout(.....));
container.add(...);
1.5-
frame.setLayout(new GridLayout(..));
frame.add(...);