簡體   English   中英

將ActionListener添加到按鈕

[英]Adding ActionListener to button

我有一個使用ShowLayout的帶有6個按鈕的應用程序。 按下按鈕時,控制台中會顯示按鈕編號。

我的代碼出了什么問題? 我無法上班! 按鈕顯示,但無法使actionListenerto工作並顯示數字。 謝謝!

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

import javax.swing.*;


class ShowFlowlayout extends JFrame implements ActionListener{

JPanel p1 = new JPanel();
JButton one = new JButton("One");
JButton two = new JButton("Two");
JButton three = new JButton("Three");
JPanel p2 = new JPanel();
JButton four = new JButton("Four");
JButton five = new JButton("Five");
JButton six = new JButton("Six");


public ShowFlowlayout() {

    this.setLayout (new FlowLayout(FlowLayout.LEFT, 10, 20));

    p1.add(one);
    p1.add(two);
    p1.add(three);
    p2.add(four);
    p2.add(five);
    p2.add(six);

    add(p1, FlowLayout.LEFT);
    add(p2, FlowLayout.CENTER);

}

 public void actionPerformed(ActionEvent e) {
        if(e.getSource() == one)
        {
            System.out.println("Button One");
        }
        if(e.getSource() == two)
        {
            System.out.println("Button Two");
        }
        if(e.getSource() == three)
        {
            System.out.println("Button Three");
        }
        if(e.getSource() == four)
        {
            System.out.println("Button Four");
        }
        if(e.getSource() == five)
        {
            System.out.println("Button Five");
        }
        if(e.getSource() == six)
        {
            System.out.println("Button Six");
        }


    }  




public static void main(String[] args) 
{
    ShowFlowlayout frame = new ShowFlowlayout();

     frame.setTitle ("Programming 12.1");
     frame.setLocationRelativeTo(null);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(440, 100);
     frame.setVisible(true);
}

`

使用按鈕注冊ActionListener

one.addActionListener(this);
two.addActionListener(this);
...

實際上你沒有將ActionListener添加到按鈕。 試試這樣:

public ShowFlowlayout() {

   this.setLayout (new FlowLayout(FlowLayout.LEFT, 10, 20)); 

   p1.add(one);
   p1.add(two);
   p1.add(three);
   p2.add(four);
   p2.add(five);
   p2.add(six);

   one.addActionListener(this);
   two.addActionListener(this);
   three.addActionListener(this);
   four.addActionListener(this);
   five.addActionListener(this);
   six.addActionListener(this);

   add(p1, FlowLayout.LEFT);
   add(p2, FlowLayout.CENTER);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM