扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞瀹炵幇鎸夐挳娣诲姞鍔熻兘

扬州沐宇科技
2023-12-12 22:46:06
Java

瑕佸疄鐜版寜閽坊鍔犲姛鑳斤紝鍙互鎸夌収浠ヤ笅姝ラ杩涜鎿嶄綔锛?/p>

  1. 鍒涘缓涓€涓寜閽璞★紝骞惰缃寜閽殑鏂囨湰銆佷綅缃拰澶у皬绛夊睘鎬с€?/p>

    JButton button = new JButton("鎸夐挳");
    button.setBounds(x, y, width, height);
    
  2. 鍒涘缓涓€涓寜閽洃鍚櫒绫伙紝瀹炵幇 ActionListener 鎺ュ彛锛屽苟閲嶅啓 actionPerformed 鏂规硶銆傚湪鏂规硶涓紪鍐欐寜閽偣鍑诲悗鐨勯€昏緫浠g爜銆?/p>

    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // 鎸夐挳鐐瑰嚮鍚庣殑閫昏緫浠g爜
        }
    }
    
  3. 灏嗘寜閽洃鍚櫒娣诲姞鍒版寜閽璞′笂銆?/p>

    button.addActionListener(new ButtonListener());
    
  4. 灏嗘寜閽坊鍔犲埌闇€瑕佹樉绀虹殑瀹瑰櫒涓紝渚嬪 JFrame銆?/p>

    JFrame frame = new JFrame();
    frame.add(button);
    

瀹屾暣鐨勭ず渚嬩唬鐮佸涓嬶細

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonExample {
    public static void main(String[] args) {
        JButton button = new JButton("鎸夐挳");
        button.setBounds(100, 100, 100, 50);

        button.addActionListener(new ButtonListener());

        JFrame frame = new JFrame();
        frame.add(button);

        frame.setSize(300, 200);
        frame.setLayout(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    static class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // 鎸夐挳鐐瑰嚮鍚庣殑閫昏緫浠g爜
            System.out.println("鎸夐挳琚偣鍑讳簡");
        }
    }
}

杩愯绀轰緥浠g爜锛岀偣鍑绘寜閽悗锛屾帶鍒跺彴灏嗚緭鍑?quot;鎸夐挳琚偣鍑讳簡"銆備綘鍙互鍦?actionPerformed 鏂规硶涓紪鍐欏叿浣撶殑鍔熻兘浠g爜鏉ュ疄鐜版寜閽偣鍑诲悗鐨勫姛鑳姐€?/p>

扫码添加客服微信