desktoptest.java

来自「这是一个java程序」· Java 代码 · 共 73 行

JAVA
73
字号
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;

public class DesktopTest extends JFrame {
   private JDesktopPane theDesktop;
   // set up GUI
   public DesktopTest(){
      super( "Using a JDesktopPane" );
      // create menu bar, menu and menu item
      JMenuBar bar = new JMenuBar();
      JMenu addMenu = new JMenu( "Add" );
      JMenuItem newFrame = new JMenuItem( "Internal Frame" );
      addMenu.add( newFrame );
      bar.add( addMenu );
      setJMenuBar( bar );
      // set up desktop
      theDesktop = new JDesktopPane();
      getContentPane().add( theDesktop );
    
      // set up listener for newFrame menu item
      newFrame.addActionListener(
         // anonymous inner class to handle menu item event
         new ActionListener() {
            // display new internal window
            public void actionPerformed( ActionEvent event ) {
               // create internal frame
               JInternalFrame frame = new JInternalFrame("Internal Frame", true, true, true, true );
               // attach panel to internal frame content pane
               Container container = frame.getContentPane();
               MyJPanel panel = new MyJPanel();
               container.add( panel, BorderLayout.CENTER );
               // set size internal frame to size of its contents
               frame.pack();
               // attach internal frame to desktop and show it
               theDesktop.add( frame );
               frame.setVisible( true );
            }
         }  // end anonymous inner class
      ); // end call to addActionListener
      setSize( 600, 440 );
      setVisible( true );
   }  // end constructor
   // execute application
   public static void main( String args[] ) {     
      DesktopTest application = new DesktopTest();
      application.setDefaultCloseOperation(
         JFrame.EXIT_ON_CLOSE );
   }
}  // end class DesktopTest
// class to display an ImageIcon on a panel
class MyJPanel extends JPanel {
   private ImageIcon imageIcon;
   // load image
   public MyJPanel() {
      imageIcon = new ImageIcon( "jhtp4.png" );
   }
   // display imageIcon on panel
   public void paintComponent( Graphics g ){
      // call superclass paintComponent method
      super.paintComponent( g );
      // display icon
      imageIcon.paintIcon( this, g, 0, 0 );
   }
   // return image dimensions
   public Dimension getPreferredSize(){
      return new Dimension( imageIcon.getIconWidth(),
         imageIcon.getIconHeight() );  
   }
}  // end class MyJPanel

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?