首页 > 代码库 > java学习笔记_GUI(5)
java学习笔记_GUI(5)
demo如何为不同的button创建对应的响应函数
1 import javax.swing.*; 2 import java.awt.event.*; 3 import java.awt.*; 4 5 class MyPanel_2 extends JPanel { 6 public void paintComponent( Graphics g ) { 7 g.fillRect(0, 0, this.getWidth(), this.getHeight()); 8 int red = (int) (Math.random() * 255); 9 int green = (int) (Math.random() * 255);10 int blue = (int) (Math.random() * 255);11 Color randomColor = new Color(red, green, blue);12 g.setColor(randomColor);13 g.fillOval(70, 40, 100, 100);14 }15 }16 17 class Gui{18 19 JButton button = new JButton("change color");20 JButton button_change_label = new JButton("change label");21 JLabel label = new JLabel("I‘m a label");22 JFrame frame = new JFrame();23 24 private void set_frame() {25 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);26 frame.setSize(800, 600);27 frame.setVisible(true);28 }29 30 public void show_my_panel() {31 set_frame();32 frame.getContentPane().add(BorderLayout.SOUTH, button);33 button.addActionListener(new ColorButtonActionListener());34 35 frame.getContentPane().add(BorderLayout.EAST, button_change_label);36 button_change_label.addActionListener(new LabelButtonActionListener() );37 38 frame.getContentPane().add(BorderLayout.WEST, label);39 40 frame.getContentPane().add(BorderLayout.CENTER,new MyPanel_2());41 }42 43 class ColorButtonActionListener implements ActionListener {44 public void actionPerformed( ActionEvent event ) {45 frame.repaint();46 }47 }48 49 class LabelButtonActionListener implements ActionListener {50 public void actionPerformed( ActionEvent event ) {51 label.setText("That hurt!");52 }53 }54 }55 56 class GuiTest {57 public static void main( String[] args ) {58 Gui gui = new Gui();59 gui.show_my_panel();60 }61 }
java学习笔记_GUI(5)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。