JFrame背风景设置.docVIP

  • 2
  • 0
  • 约2.72万字
  • 约 5页
  • 2017-05-25 发布于河南
  • 举报
JFrame背风景设置

在Java的GUI设计中,Frame和JFrame两者之间有很大差别, 如果不认真会有不必要的麻烦,例如GUI背景色的添加为例: import java.lang.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainWindows extends JFrame{ ??private MainWindows ContentPane; ? ? public MainWindows(){ ??this.setLayout(null); ??this.setTitle(题库抽题系统); ??this.setBounds(0,0,800,600); ??this.setBackground(Color.RED);//改成this.getContentPane().setBackground(Color.RED);即可 ? this.addWindowListener( new WindowAdapter(){ ???? public void windowClosing(WindowEvent e){ ??????? System.exit(0); ???? }); ? } ??this.setVisible(true); ??ContentPane=this; ???}?? } ? 该程序运行后背景色并没有变成RED,但是将第5行改成extends Frame就能改背景色,那么为什么JFrame不行,原因是Frame和JFrame的窗口层次结构不同,具体可参考中国铁道出版社的《Java 完美经典》一书。JFrame的窗口包括:JFrame、Root Pane、Layered pane、Content Pane、Glass Pane;而Frmae窗口包括:Frame、Content Pane。所以解决的办法是将“this.setBackground(Color.RED);”代码改成“this.getContentPane().setBackground(Color.RED);”即可。 例子: class MyFrame extends JFrame{ MyFrame(){ setBounds(400,300,440,330); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBackground(Color.blue); //那就是不能给JFrame设置颜色?? setVisible(true); } void getPane(){ JComponent rootPane =(JComponent) getRootPane(); //返回值类型container 现在把它看成Container 当然不能用JComponent中的方法 JComponent layeredPane =(JComponent) getLayeredPane();//返回值类型是JLayeredpane JComponent contentPane =(JComponent) getContentPane();//返回值的类型是Container JComponent glassPane =(JComponent) getGlassPane(); //返回值的类型是Compoent //这也充分说明这些方法中都是用JPanel实现,但返回值却反回了父类 //设置所有面板透明 rootPane.setOpaque(false); layeredPane.setOpaque(false); contentPane.setOpaque(false); glassPane.setOpaque(false); rootPane.setVisible(false); layeredPane.setVisible(false); contentPane.setVisible(false); glassPane.setVisible(false); rootPane.setBackground(Color.blue); layeredPane.setBackground(Color.blue); contentPane.setBackground(Color.cyan); glassPane.setBackground(Color.green); ——fyg } }

文档评论(0)

1亿VIP精品文档

相关文档