窗体添加按钮的问题
程序代码:
import javax.swing.*; import java.awt.*; public class Window1 { public static void main(String[] args) { JFrame Win1=new JFrame("第一个窗体"); BorderLayout Layout=new BorderLayout(); Win1.getContentPane().setLayout(null); Win1.setBounds(100,100,500,500); Win1.getContentPane().setBackground(Color.white);//为什么要getContentPane()? JButton Btn1=new JButton("Command1"); Btn1.setBounds(10,10,150,50); Btn1.setVisible(true); Btn1.setForeground(Color.red); Win1.setVisible(true); //Win1.getContentPane().add(Btn1); //为什么一定要这句才能添加一个按钮? Win1.add(Btn1); }
运行出现以下错误:
java.lang.Error: Do not use javax.swing.JFrame.add() use javax.swing.JFrame.getContentPane().add() instead
at javax.swing.JFrame.createRootPaneException(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
改用Win1.getContentPane().add(Btn1); 才可以正常添加,为什么?