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

public class filecabinet extends JFrame implements ActionListener {

    private String folder = "";
    //create buttons

    private JButton a = new JButton("A");
    private JButton b = new JButton("B");
    private JButton c = new JButton("C");
    private JButton d = new JButton("D");
    private JButton e = new JButton("E");
    private JButton f = new JButton("F");
    private JButton g = new JButton("G");
    private JButton h = new JButton("H");
    private JButton i = new JButton("I");
    private JButton j = new JButton("J");
    private JButton k = new JButton("K");
    private JButton l = new JButton("L");
    private JButton m = new JButton("M");
    private JButton n = new JButton("N");
    private JButton o = new JButton("O");
    private JButton p = new JButton("P");
    private JButton q = new JButton("Q");
    private JButton r = new JButton("R");
    private JButton s = new JButton("S");
    private JButton t = new JButton("T");
    private JButton u = new JButton("U");
    private JButton v = new JButton("V");
    private JButton w = new JButton("W");
    private JButton x = new JButton("X");
    private JButton y = new JButton("Y");
    private JButton z = new JButton("Z");
    //create panels
    private JPanel aF = new JPanel();
    private JPanel gL = new JPanel();
    private JPanel mR = new JPanel();
    private JPanel sX = new JPanel();
    private JPanel yZ = new JPanel();
    private JPanel readout = new JPanel();
    private JLabel notify = new JLabel("You have selected folder " + folder);

    public void ComposePane(){
        //set buttons to panels
        aF.add(a);
        aF.add(b);
        aF.add(c);
        aF.add(d);
        aF.add(e);
        aF.add(f);
        //set layout of panels
        aF.setLayout(new GridLayout(2,3));
        gL.add(g);
        gL.add(h);
        gL.add(i);
        gL.add(j);
        gL.add(k);
        gL.add(l);
        gL.setLayout(new GridLayout(2,3));
        mR.add(m);
        mR.add(n);
        mR.add(o);
        mR.add(p);
        mR.add(q);
        mR.add(r);
        mR.setLayout(new GridLayout(2,3));
        sX.add(s);
        sX.add(t);
        sX.add(u);
        sX.add(v);
        sX.add(w);
        sX.add(x);
        sX.setLayout(new GridLayout(2,3));
        yZ.add(y);
        yZ.add(z);
        yZ.add(readout);
        readout.add(notify);
        yZ.setLayout(new GridLayout(2,3));
    }
    public filecabinet(){
        setTitle("File Cabinet");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(5,1));
        ComposePane();
        add(aF);
        add(gL);
        add(mR);
        add(sX);
        add(yZ);
        addActionListener();
    }


    public void actionPerformed(ActionEvent e) {
        folder = ((JButton) e.getSource()).getText();


    }
    public void addActionListener(){
        a.addActionListener(this);
        b.addActionListener(this);
        c.addActionListener(this);
        d.addActionListener(this);
        e.addActionListener(this);
        f.addActionListener(this);
        g.addActionListener(this);
        h.addActionListener(this);
        i.addActionListener(this);
        j.addActionListener(this);
        k.addActionListener(this);
        l.addActionListener(this);
        m.addActionListener(this);
        n.addActionListener(this);
        o.addActionListener(this);
        p.addActionListener(this);
        q.addActionListener(this);
        r.addActionListener(this);
        s.addActionListener(this);
        t.addActionListener(this);
        u.addActionListener(this);
        v.addActionListener(this);
        w.addActionListener(this);
        x.addActionListener(this);
        y.addActionListener(this);
        z.addActionListener(this);

    }
    public static void main(String[]args){
        filecabinet frame = new filecabinet();
        final int WIDTH = 600;
        final int HEIGHT = 600;
        frame.setSize(WIDTH, HEIGHT);
        frame.setVisible(true);
    }

}

我宁愿不必为每个按钮都写出一个监听器,如果我能得到按钮中包含的文本,我就在徘徊。

例如“您已选择文件夹 X”,X 是选择的按钮。

4

4 回答 4

3

同样,要么使用数组和/或 for 循环来整合您的代码,从而摆脱代码冗余。例如:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class FileCabinet2 extends JPanel {
   public static final char FIRST_LETTER = 'A';
   public static final char LAST_LETTER = 'Z';
   private static final float lARGE_FONT_POINTS = 32f;
   private static final int GRID_COLS = 3;
   private JLabel chosenLabel = new JLabel();

   public FileCabinet2() {
      JPanel letterPanel = new JPanel(new GridLayout(0, GRID_COLS));
      ActionListener btnListener = new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent evt) {
            chosenLabel.setText(evt.getActionCommand());
         }
      };
      for (char c = FIRST_LETTER; c <= LAST_LETTER; c++) {
         String buttonTitle = String.valueOf(c);
         JButton button = new JButton(buttonTitle);
         setFontPoints(button, lARGE_FONT_POINTS);
         letterPanel.add(button);

         button.addActionListener(btnListener);
      }

      JLabel selectionLabel = new JLabel("Selection: ", SwingConstants.RIGHT);
      setFontPoints(selectionLabel, lARGE_FONT_POINTS);
      setFontPoints(chosenLabel, lARGE_FONT_POINTS);


      JPanel bottomPanel = new JPanel(new GridLayout(1, 0));
      bottomPanel.add(selectionLabel);
      bottomPanel.add(chosenLabel);
      bottomPanel.setBorder(BorderFactory.createEtchedBorder());

      setLayout(new BorderLayout());
      add(letterPanel, BorderLayout.CENTER);
      add(bottomPanel, BorderLayout.PAGE_END);
   }

   private void setFontPoints(JComponent jComp, float points) {
      jComp.setFont(jComp.getFont().deriveFont(points));
   }

   private static void createAndShowGui() {
      FileCabinet2 mainPanel = new FileCabinet2();

      JFrame frame = new JFrame("File Cabinet");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

现在如果你想改变按钮列的数量,你只需要改变一个常量,GRID_COLS,字体大小也一样,只需要改变LARGE_FONT_POINTS。

在此处输入图像描述

于 2013-04-19T04:49:59.360 回答
2

为了这:

宁愿不必为每个按钮写出一个监听器

创建一个接受JPanel作为参数的方法,然后迭代到 中的每个组件JPanel,如果组件是,则添加动作侦听器JButton

这个:

I was wandering if I could just get the text contained in the button.

只需在JLabel. 您已经获得了按钮内容吗?

所以,完整的代码是:

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

public class filecabinet extends JFrame implements ActionListener {

    private String folder = "";
    // create buttons

    private JButton a = new JButton("A");
    private JButton b = new JButton("B");
    private JButton c = new JButton("C");
    private JButton d = new JButton("D");
    private JButton e = new JButton("E");
    private JButton f = new JButton("F");
    private JButton g = new JButton("G");
    private JButton h = new JButton("H");
    private JButton i = new JButton("I");
    private JButton j = new JButton("J");
    private JButton k = new JButton("K");
    private JButton l = new JButton("L");
    private JButton m = new JButton("M");
    private JButton n = new JButton("N");
    private JButton o = new JButton("O");
    private JButton p = new JButton("P");
    private JButton q = new JButton("Q");
    private JButton r = new JButton("R");
    private JButton s = new JButton("S");
    private JButton t = new JButton("T");
    private JButton u = new JButton("U");
    private JButton v = new JButton("V");
    private JButton w = new JButton("W");
    private JButton x = new JButton("X");
    private JButton y = new JButton("Y");
    private JButton z = new JButton("Z");
    // create panels
    private JPanel aF = new JPanel();
    private JPanel gL = new JPanel();
    private JPanel mR = new JPanel();
    private JPanel sX = new JPanel();
    private JPanel yZ = new JPanel();
    private JPanel readout = new JPanel();
    private JLabel notify = new JLabel("You have selected folder " + folder);

    public void ComposePane() {
        // set buttons to panels
        aF.add(a);
        aF.add(b);
        aF.add(c);
        aF.add(d);
        aF.add(e);
        aF.add(f);
        // set layout of panels
        aF.setLayout(new GridLayout(2, 3));
        gL.add(g);
        gL.add(h);
        gL.add(i);
        gL.add(j);
        gL.add(k);
        gL.add(l);
        gL.setLayout(new GridLayout(2, 3));
        mR.add(m);
        mR.add(n);
        mR.add(o);
        mR.add(p);
        mR.add(q);
        mR.add(r);
        mR.setLayout(new GridLayout(2, 3));
        sX.add(s);
        sX.add(t);
        sX.add(u);
        sX.add(v);
        sX.add(w);
        sX.add(x);
        sX.setLayout(new GridLayout(2, 3));
        yZ.add(y);
        yZ.add(z);
        yZ.add(readout);
        readout.add(notify);
        yZ.setLayout(new GridLayout(2, 3));
    }

    public filecabinet() {
        setTitle("File Cabinet");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(5, 1));
        ComposePane();
        add(aF);
        add(gL);
        add(mR);
        add(sX);
        add(yZ);
        addActionListener(aF);
        addActionListener(gL);
        addActionListener(mR);
        addActionListener(sX);
        addActionListener(yZ);
    }

    public void actionPerformed(ActionEvent e) {
        folder = ((JButton) e.getSource()).getText();
            // set the label with folder value
        notify.setText("You have selected folder " + folder);

    }

    // Attach event handler to each JButton in JPanel
    public void addActionListener(JPanel panel) {
        Component[] components = panel.getComponents();
        for (Component component : components) {
            if (component instanceof JButton) {
                ((JButton) component).addActionListener(this);
            }
        }
    }

    public static void main(String[] args) {
        filecabinet frame = new filecabinet();
        final int WIDTH = 600;
        final int HEIGHT = 600;
        frame.setSize(WIDTH, HEIGHT);
        frame.setVisible(true);
    }

}
于 2013-04-19T00:56:19.347 回答
2
  • 快速审查您的代码,将您的代码缩短到这个长度。想象一下,如果你给它更多的洞察力,你可以实现什么。
  • 此外,当您在代码中看到这一点时,您会一次又一次地为同一件事重复一些行,您确实可以想到一种模式,它可以以正确的方式为您完成这项工作,而且击键次数更少。

试试你的这个修改过的代码:-)

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

public class Filecabinet extends JFrame implements ActionListener {

    private String folder = "";
    //create buttons
    private JButton[] button = new JButton[26];

    //create panels
    private JPanel aF = new JPanel();
    private JPanel gL = new JPanel();
    private JPanel mR = new JPanel();
    private JPanel sX = new JPanel();
    private JPanel yZ = new JPanel();
    private JPanel readout = new JPanel();
    private JLabel notify = new JLabel("You have selected folder " + folder);

    public void ComposePane(){
        init_Buttons(button);
        //set buttons to panels
        for (int i = 0; i < 6; i++)
            aF.add(button[i]);
        //set layout of panels
        aF.setLayout(new GridLayout(2,3));
        for (int i = 6; i < 12; i++)
            gL.add(button[i]);
        gL.setLayout(new GridLayout(2,3));
        for (int i = 12; i < 18; i++)
            mR.add(button[i]);
        mR.setLayout(new GridLayout(2,3));
        for (int i = 18; i < 24; i++)
            sX.add(button[i]);
        sX.setLayout(new GridLayout(2,3));
        for (int i = 24; i < 26; i++)
            yZ.add(button[i]);
        yZ.add(readout);
        readout.add(notify);
        yZ.setLayout(new GridLayout(2,3));
    }

    private void init_Buttons(JButton[] button)
    {
        int value = 65;
        for (int i = 0; i < button.length; i++)
        {
            button[i] = new JButton(Character.toString((char) value++));
            button[i].addActionListener(this);
        }
    }
    public Filecabinet(){
        setTitle("File Cabinet");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(5,1));
        ComposePane();
        add(aF);
        add(gL);
        add(mR);
        add(sX);
        add(yZ);
    }


    public void actionPerformed(ActionEvent e) {
        folder = ((JButton) e.getSource()).getText();

        notify.setText(folder);
    }

    public static void main(String[]args){

        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                Filecabinet frame = new Filecabinet();
                final int WIDTH = 600;
                final int HEIGHT = 600;
                //frame.setSize(WIDTH, HEIGHT);
                frame.pack();
                frame.setVisible(true);
            }
        });        
    }

}
于 2013-04-19T03:38:20.763 回答
1

您可以子类JButton化并为子类编写一个构造函数,该构造函数将作为参数接收到动作侦听器的引用,您的JFrame.

例如,您的子类可能只是:

public class YourButton extends JButton {
    public YourButton(String title, ActionListener listener) {
        super(title);
        this.addActionListener(listener);
    }
}

所以而不是:

private JButton a = new JButton("A");

你会打电话给:

private YourButton a = new YourButton("A", this);

此外,正如其他人所建议的,您的actionPerformed(ActionEvent e)方法要求您更新通知JLabel实例以反映所选按钮的标题。

希望有帮助!

于 2013-04-19T01:08:42.423 回答