java鎬庝箞瀹炵幇鎸夐挳娣诲姞鍔熻兘
瑕佸疄鐜版寜閽坊鍔犲姛鑳斤紝鍙互鎸夌収浠ヤ笅姝ラ杩涜鎿嶄綔锛?/p>
-
鍒涘缓涓€涓寜閽璞★紝骞惰缃寜閽殑鏂囨湰銆佷綅缃拰澶у皬绛夊睘鎬с€?/p>
JButton button = new JButton("鎸夐挳"); button.setBounds(x, y, width, height);
-
鍒涘缓涓€涓寜閽洃鍚櫒绫伙紝瀹炵幇 ActionListener 鎺ュ彛锛屽苟閲嶅啓 actionPerformed 鏂规硶銆傚湪鏂规硶涓紪鍐欐寜閽偣鍑诲悗鐨勯€昏緫浠g爜銆?/p>
class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { // 鎸夐挳鐐瑰嚮鍚庣殑閫昏緫浠g爜 } }
-
灏嗘寜閽洃鍚櫒娣诲姞鍒版寜閽璞′笂銆?/p>
button.addActionListener(new ButtonListener());
-
灏嗘寜閽坊鍔犲埌闇€瑕佹樉绀虹殑瀹瑰櫒涓紝渚嬪 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>
相关问答