Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 相同的actionhandler,多个按钮_Java_Swing_Jframe - Fatal编程技术网

Java 相同的actionhandler,多个按钮

Java 相同的actionhandler,多个按钮,java,swing,jframe,Java,Swing,Jframe,我正在使用JFrame创建一个应用程序,我想知道如何将同一个actionhandler设置为不同的按钮。在我的应用程序中,我有8个按钮,一旦你点击它们,它们就会消失。每个按钮都会发生“消失的事情”,但在这之后,每个按钮都会做一些不同的事情。所以我想通过这样做来节省一些线路,但我不知道怎么做 以下代码解释了我的意思: import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import

我正在使用JFrame创建一个应用程序,我想知道如何将同一个actionhandler设置为不同的按钮。在我的应用程序中,我有8个按钮,一旦你点击它们,它们就会消失。每个按钮都会发生“消失的事情”,但在这之后,每个按钮都会做一些不同的事情。所以我想通过这样做来节省一些线路,但我不知道怎么做

以下代码解释了我的意思:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class StackOverflowExample {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StackOverflowExample window = new StackOverflowExample();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public StackOverflowExample() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("New button");
        JButton btnNewButton_1 = new JButton("New button");
        JButton btnNewButton_2 = new JButton("New button");
        JButton btnNewButton_3 = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {


                initialize2();
            }
        });
        btnNewButton.setBounds(75, 51, 89, 23);
        frame.getContentPane().add(btnNewButton);

        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                btnNewButton.setVisible(false);
                btnNewButton_1.setVisible(false);
                btnNewButton_2.setVisible(false);
                btnNewButton_3.setVisible(false);
                initialize2();
            }
        });
        btnNewButton_1.setBounds(75, 85, 89, 23);
        frame.getContentPane().add(btnNewButton_1);


        btnNewButton_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                btnNewButton.setVisible(false);
                btnNewButton_1.setVisible(false);
                btnNewButton_2.setVisible(false);
                btnNewButton_3.setVisible(false);
                initialize2();
            }
        });
        btnNewButton_2.setBounds(75, 119, 89, 23);
        frame.getContentPane().add(btnNewButton_2);


        btnNewButton_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                btnNewButton.setVisible(false);
                btnNewButton_1.setVisible(false);
                btnNewButton_2.setVisible(false);
                btnNewButton_3.setVisible(false);
                initialize2();
            }
        });
        btnNewButton_3.setBounds(75, 153, 89, 23);
        frame.getContentPane().add(btnNewButton_3);
    }
    private void initialize2(){

        /*here I'll put the code for my new frame.
          I'll make like some more buttons and a textfield. 
        */
    }
}

如果您试图使所有组件消失并被其他“视图”替换,那么最简单的方法是使用CardLayout,然后在按下按钮时调用此对象的
show(…)
方法来显示所选视图,如下所示。请注意,每个按钮都有自己的
ButtonAction
对象,它扩展了AbstractAction。这有点像“类固醇”上的ActionListener,因为它有一个
actionPerformed(…)
方法,当按下按钮时会调用该方法,就像ActionListener一样,但这里我们也设置按钮的文本,我们可以根据需要设置其助记符和/或图标,我们还可以与其他类似按钮的对象(如JMenuItems)共享操作

还要注意的是,我尽一切努力避免
null
布局和
setBounds(…)
。虽然空布局和
setBounds()
可能会像创建复杂GUI的最简单和最好的方式一样吸引新手,但您创建的GUI越多,在使用它们时遇到的困难就越严重。当GUI调整大小时,它们不会调整您的组件的大小,它们是一个需要增强或维护的皇家女巫,当它们放置在滚动窗格中时会完全失败,当在所有平台或屏幕分辨率与原始分辨率不同的情况下查看时,它们看起来非常糟糕

import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class SeveralButtons extends JPanel {
   // preferred size dimensions
   private static final int PREF_W = 450;
   private static final int PREF_H = 300;

   // number of buttons displayed
   private static final int BUTTON_COUNT = 4;
   public static final String BLANK_PANEL = "blank";
   public static final String MAIN_PANEL = "main panel";
   private CardLayout cardLayout = new CardLayout();

   public SeveralButtons() {
      // create JPanel to hold our buttons. use a grid layout with 1 column
      JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 5, 5));
      for (int i = 0; i < BUTTON_COUNT; i++) {
          // create a new JButton and give it a an Action
         JButton button = new JButton(new ButtonAction(i));
         // add it to the buttonPanel
         buttonPanel.add(button);
      }

      // main JPanel to hold the buttonPanel
      JPanel mainPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
      mainPanel.add(buttonPanel);

      // set this class's layout
      setLayout(cardLayout);
      add(mainPanel, MAIN_PANEL); // add mainPanel
      add(new JPanel(), BLANK_PANEL);  // add a blank JPanel
   }

   @Override // so JPanel will be at least our desired size
   public Dimension getPreferredSize() {
      Dimension superSz = super.getPreferredSize();
      if (isPreferredSizeSet()) {
         return superSz;
      }
      int prefW = Math.max(superSz.width, PREF_W);
      int prefH = Math.max(superSz.height, PREF_H);
      return new Dimension(prefW, prefH);
   }

   // our AbstractAction class, an ActionListener "on steroids"
   private class ButtonAction extends AbstractAction {
      private int value;

      public ButtonAction(int i) {
         String name = "Button " + i;
         putValue(NAME, name);
         this.value = i;
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // TODO: do some number specific action based on value
         // For a trivial example:
         String message = "Button pressed: " + value;
         JOptionPane.showMessageDialog((Component) e.getSource(), message);

         // swap view to a blank view
         cardLayout.show(SeveralButtons.this, BLANK_PANEL);
      }
   }

   // create and display GUI in a thread-safe manner
   private static void createAndShowGui() {
      SeveralButtons mainPanel = new SeveralButtons();

      JFrame frame = new JFrame("SeveralButtons");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
         }
      });
   }
}
导入java.awt.CardLayout;
导入java.awt.Component;
导入java.awt.Dimension;
导入java.awt.FlowLayout;
导入java.awt.GridLayout;
导入java.awt.event.ActionEvent;
导入javax.swing.*;
@抑制警告(“串行”)
公共类的几个按钮扩展了JPanel{
//首选尺寸
私有静态最终整型参数W=450;
私有静态最终整型参数H=300;
//显示的按钮数
私有静态最终整数按钮计数=4;
公共静态最终字符串BLANK\u PANEL=“BLANK”;
公共静态最终字符串MAIN\u PANEL=“MAIN PANEL”;
private CardLayout CardLayout=新的CardLayout();
公共几个按钮(){
//创建JPanel来保存按钮。使用一列的网格布局
JPanel buttonPanel=新的JPanel(新的网格布局(0,1,5,5));
对于(int i=0;i<按钮计数;i++){
//创建一个新的JButton并给它一个动作
JButton按钮=新JButton(新按钮操作(i));
//将其添加到buttonPanel
按钮面板。添加(按钮);
}
//固定按钮面板的主面板
JPanel主面板=新的JPanel(新的FlowLayout(FlowLayout.LEADING));
主面板。添加(按钮面板);
//设置该类的布局
设置布局(卡片布局);
添加(主面板,主面板);//添加主面板
add(new JPanel(),BLANK_面板);//添加一个空白JPanel
}
@重写//以便JPanel至少是我们所需的大小
公共维度getPreferredSize(){
维度superSz=super.getPreferredSize();
如果(isPreferredSizeSet()){
返回superSz;
}
int prefW=Math.max(superSz.width,PREF_W);
int prefH=Math.max(superSz.height,PREF_H);
返回新维度(prefW、prefH);
}
//我们的AbstractAction类,ActionListener“使用类固醇”
私有类按钮操作扩展了AbstractAction{
私有int值;
公共按钮(int i){
String name=“Button”+i;
putValue(名称、名称);
该值=i;
}
@凌驾
已执行的公共无效操作(操作事件e){
//TODO:根据值执行一些特定于数字的操作
//举个简单的例子:
字符串消息=“按下按钮:”+值;
showMessageDialog((组件)e.getSource(),message);
//将视图交换为空白视图
cardLayout.show(几个按钮,此为空白面板);
}
}
//以线程安全的方式创建和显示GUI
私有静态void createAndShowGui(){
SeverbalButtons主面板=新的SeverbalButtons();
JFrame=新的JFrame(“几个按钮”);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(主面板);
frame.pack();
frame.setLocationByPlatform(真);
frame.setVisible(true);
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
createAndShowGui();
}
});
}
}

您应该首先创建一个actionlistener:

CustomActionListener actionListener = new CustomActionListener();
然后将actionListener添加到每个按钮,如:

btnNewButton.addActionListener(actionListener);
然后创建一个名为CustomActionListener的内部类,如下所示:

public class CustomActionListener implements ActionListener{
    public void actionPerformed(ActionEvent e){ 
        //Code you want to perform when a button is pressed.
    }
}

“这是解释我的意思的代码:…”
——对不起,我还是不明白。你到底想干什么?这段代码做了什么不应该做的事情?它不应该做什么?只需将相同的
ActionListener
添加到所有按钮。将您的匿名侦听器分配给一个变量,并使用该变量调用每个按钮的
addActionListener
,或者创建一个concreate
ActionListener
类,或者让您的类继承自
ActionListener
。另外,您的代码包含许多Swing新手问题,包括使用带有
setBounds(…)
的空布局,提到使用多个JFrames,这两种情况都应该避免。看起来你真的想使用卡片布局,而不是将多个组件设置为不可见。你真是个神。你解释得很好。当我达到15岁时,我一定会听取你的意见。