【问题标题】:GridLayout JButton JOptionPane with ActionListener for each buttonGridLayout JButton JOptionPane 与每个按钮的 ActionListener
【发布时间】:2018-10-05 23:11:03
【问题描述】:

我正在制作一款日本约会游戏风格的约会游戏,其中包含图片和回复,以供娱乐和练习。我试图为网格布局中的每个按钮显示一个JOptionPane 消息对话框,作为对每个选项的响应。这样,它就像一棵逻辑树。我不习惯使用动作监听器,因为我有点初学者。这是我的代码。我只是不习惯这样做的语法。

谁能帮帮我?

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.*;
//Implementations of packages

public class NestedPanels extends JPanel {
   private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
   private static final int TITLE_POINTS = 3; //number of objects in text box

   public NestedPanels() { //implemeted class
      JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
      for (String btnText : BTN_TEXTS) { //BTN TEXT button titles linked to string btnText label
         southBtnPanel.add(new JButton(btnText)); //add btnText label
      }
      setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
      setLayout(new BorderLayout());
      add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
      add(southBtnPanel, BorderLayout.SOUTH);
   }

   private static void createAndShowGui() {//class to show gui
        NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
        JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setVisible(true);
        ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
        JLabel label = new JLabel(icon);
        mainPanel.add(label);
        frame.setDefaultCloseOperation
        (JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
   }

   public static void main(String[] args) {
        System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");

        Scanner in = new Scanner(System.in);

        String confirm = in.nextLine();

        if (confirm.equalsIgnoreCase("Yes")) {
            System.out.println("Ok hot stuff... Let's start.");

            NestedPanels mainPanel = new NestedPanels();
        } else {
            System.out.println("Maybe some other time!");

            return;
        }

         SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

【问题讨论】:

  • 我不明白你想要达到什么目的。但是,JOptionPane 是一个临时对话框,它显示(通常带有一条消息),从用户那里获取一些数据,然后关闭。所以你不应该在 GUI 上使用扫描仪。而是使用 JOptionPane 为用户显示消息。阅读How to Make Dialogs 上的 Swing 教程以获取更多信息和示例。本教程还有一个关于如何编写 ActionListener 的部分。
  • Swing 教程介绍了这三种编写动作监听器的方法: 要编写动作监听器,请按照以下步骤操作: 声明一个事件处理程序类并指定该类要么实现一个 ActionListener 接口,要么扩展一个实现 ActionListener 接口的类。例如: public class MyClass implements ActionListener { 但是我已经实例化了一个扩展jpanel的父类?有什么帮助吗?扫描仪只是利用我所知道的风格和品味

标签: java swing jbutton actionlistener joptionpane


【解决方案1】:

查看以下内容以了解如何将动作侦听器添加到按钮。
请注意 cmets:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class NestedPanels extends JPanel {

    private static final String[] BTN_TEXTS = { "Say Hello", "Say You Look Good", "Say Sorry I'm Late" }; //three buttons
    //never used :   private static final int TITLE_POINTS = 3;
    public NestedPanels() {

        JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1));
        for (String btnText : BTN_TEXTS) {
            JButton b = new JButton(btnText);
            //add action listener
            b.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    buttonClicked(e);//when button clicked, invoke method
                }
            });

            //alternative much shorter way to add action listener:
            //b.addActionListener(e -> buttonClicked());
            southBtnPanel.add(b);
        }
        setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
        setLayout(new BorderLayout());

        //this adds Box to the default  BorderLayout.CENTER position
        add(Box.createRigidArea(new Dimension(600, 600)));

        add(southBtnPanel, BorderLayout.SOUTH);
    }

    //respond to button clicked
    private void buttonClicked(ActionEvent e) {
        String msg = ((JButton)e.getSource()).getActionCommand()+" pressed" ;
        JOptionPane.showMessageDialog(this, msg ); //display button Action
    }

    private static void createAndShowGui() {
        NestedPanels mainPanel = new NestedPanels();
        JFrame frame = new JFrame("Date Sim 1.0");
        //no need to invoke twice frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //no need to invoke twice  frame.pack();
        //no need to invoke twice frame.setVisible(true);

        frame.getContentPane().add(mainPanel);

        /*
         * when posting images, use web resources that anyone can access
         *
        ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
        JLabel label = new JLabel(icon);

        *this adds label to the default BorderLayout.CENTER position, which is already taken by
        *the Box. Only one (last) component will be added
        mainPanel.add(label);
        *
        */

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //remove all code which is not essential to the question
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGui();
            }
        });
    }
}

【讨论】:

  • 反正有图片(将来会在网络上托管)和borderLayout.CENTER上的按钮吗?关键是让按钮像约会模拟游戏一样改变图片。先感谢您。我能够使按钮按下,但取出了图片。
  • "反正有图片(将来会在网络上托管)和borderLayout.CENTER上的按钮吗?"请发布一个新问题。当你在这里给我留言时,我会尽力回答。
【解决方案2】:

但是我已经实例化了一个扩展jpanel的父类

你看教程中提供的示例代码了吗???

那里的例子“

... extends JFrame implements ActionListener

所以你只需要:

... extends JPanel implements ActionListener

或者,如果您需要多个 ActionListener,则可以使用更灵活的方法来创建自定义类。

您可以为ActionListener 使用“匿名内部类”。比如:

ActionListener al = new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)e.getSource();
        String text = button.getText();
        Window window = SwingUtilities.windowForComponent(button);
        JOptionPane.showMessageDialog(window, text);
    }
};

然后,当您创建按钮时,您会这样做:

for (String btnText : BTN_TEXTS) 
{
     JButton button = new JButton( btnText );
     button.addActionListener( al );
     southBtnPanel.add( button );
}

【讨论】:

  • 现在 Java 抱怨“NestedPanels”不是抽象的,并且不会覆盖动作侦听器中的抽象方法 actionperformed(ActionEvent)。尝试手动 @Override 但说不适用。
  • 尝试了 actionperformed 方法:@Override public void actionPerformed(ActionEvent e) {
  • Now Java is complaining that "NestedPanels" is not abstract and does not override abstract method actionperformed(ActionEvent) in action listener. - 你有没有阅读教程并下载代码来编译和测试它?本教程清楚地向您展示了如何做到这一点。我猜不出你在做什么,因为你没有包含你的代码。所以阅读教程
  • 该方法有效。我只是阅读了教程并使用了来自 camickr 的一些代码。接下来是使用托管在 Internet 上的照片以及使用每个按钮的不同对话框。谢谢!
  • @wekruez The methodology works - 为什么答案未被接受?你得到了你的问题的答案。您获得了 Swing 教程的链接,该教程现在是未来 Swing 问题的参考。您设法将我给您的信息与教程信息结合起来,自行解决问题。如果事实上由于教程链接,您现在知道根据情况使用 ActionListener 的 3 种不同方法。这种方法还展示了如何重用相同的 ActionListener,而不是为每个按钮创建一个新的 ActionListener。这是一个很好的程序设计,因为它可以节省资源。
猜你喜欢
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 2012-11-27
  • 2016-09-02
  • 2012-12-26
  • 2020-11-01
相关资源
最近更新 更多