GUIExample.java
资源名称:task2.rar [点击查看]
上传用户:hcljs2008
上传日期:2022-07-05
资源大小:3k
文件大小:2k
源码类别:
按钮控件
开发平台:
Java
- import java.awt.BorderLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class GUIExample extends JFrame {
- private JLabel label;
- private JButton button1;
- private JButton button2;
- public static void main(String[] args) {
- GUIExample myApp = new GUIExample();
- myApp.setVisible(true);
- }
- public GUIExample() {
- this.setSize(800, 600);
- this.setResizable(false);
- label = new JLabel("THIS IS A TEXT");
- this.add(label, BorderLayout.CENTER);
- button1 = new JButton("SOUTH");
- this.add(button1, BorderLayout.SOUTH);
- button2 = new JButton("NORTH");
- this.add(button2, BorderLayout.NORTH);
- /*
- ActionListener listener = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent arg0) {
- label.setText(button.getText());
- }
- };
- button.addActionListener(listener);
- */
- button1.addActionListener(new MyListener());
- button2.addActionListener(new MyListener());
- }
- class MyListener implements ActionListener {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() instanceof JButton) {
- label.setText(((JButton) e.getSource()).getText());
- }
- /*
- if (e.getSource() == button1) {
- label.setText(button1.getText());
- } else if (e.getSource() == button2) {
- label.setText(button2.getText());
- }
- */
- }
- }
- }