首页 > 代码库 > java学习笔记_GUI(3)

java学习笔记_GUI(3)

如何加入自己定义的Panel

 1 import javax.swing.*; 2 import java.awt.event.*; 3 import java.awt.*; 4  5 class MyPanel extends JPanel { 6     public void paintComponent( Graphics g ) { 7         g.setColor( Color.orange ); 8         g.fillRect(20, 50, 100, 100); 9     }10 }11 12 13 class Gui implements ActionListener{14     15     JButton button = new JButton("click me");16     JFrame frame = new JFrame();17     18     private void set_frame() {19         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);20         frame.setSize(300, 200);21         frame.setVisible(true);22     }23 24     public void show_button() {25         set_frame();26         frame.getContentPane().add(button);27         button.addActionListener(this);28     }29     30     public void show_my_panel() {31         set_frame();32         frame.getContentPane().add(new MyPanel());33     }34     35     public void actionPerformed( ActionEvent event ) {36         button.setText("I‘ve been clicked!");37     }38 }39 40 class GuiTest {41     public static void main( String[] args ) {42         Gui gui = new Gui();43         if ( args.length > 0 ) {44             gui.show_my_panel();45         }46         else {47             gui.show_button();48         }49     }50 }

 

java学习笔记_GUI(3)