需要JButton事件的支持 [英] Need support with JButton events

查看:81
本文介绍了需要JButton事件的支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近回答了有关如何在另一个类的main方法中打开登录面板的问题。
因为我还没有接受Swing的任何课程(只有基本的Java编程),我已经偶然发现了另一个问题。

I've recently had a question answered about how to open a login panel in my main method in another class. Because i have not yet had any lessons in Swing yet (only basic Java Programming) i have already stumbled upon another question.

我怎样才能检测到用户按下JPanel中的按钮并使其执行某些操作。

How can i detect if a user has pressed a button in the JPanel and make it do something.

例如:
用户按下登录 - > if(textfield1.getText()== user){打开另一个JFrame} - >等等。

For example: User pressed login -> if (textfield1.getText() == "user"){ open another JFrame } -> etc.

这是我的主要代码:

import java.awt.*;
import javax.swing.*;

public class Corendon {

    public static void main(String[] args) {
           showLogin();
    }

    private static void showLogin(){
        Login login = new Login();

        JFrame loginFrame = new JFrame();
        loginFrame.add(login);
        loginFrame.pack();
        loginFrame.setLocationRelativeTo(null);
        loginFrame.setVisible(true);
        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

这是Login类:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Daan
 */
public class Login extends javax.swing.JPanel {

    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNINGds: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jTextField1 = new javax.swing.JTextField();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\Daan\\Dropbox\\HvA\\Programming\\Corendon\\corendon.png")); // NOI18N

        jLabel2.setText("Username");

        jLabel3.setText("Password");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dutch", "English" }));

        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel1))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(29, 29, 29)
                                .addComponent(jButton2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1))
                            .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addGap(35, 35, 35))
        );
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    }                                        

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   


}

所以我尝试在Login.java中工作并使用私有方法,它是一个事件处理程序。我做了类似的事情:

So i tried working inside the Login.java and use the private method which is an event-handler. I made it something like:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String user = jTextField1.getText();
    if(user == "user")  {
         jTextField1.setText("LOL");
    }
}  

只是为了测试它是否真的做了我想要的,但是当我按下按钮时它没有做任何事情。之后我尝试在我的main.java中实现它,其中我实际创建了带有JPanel的框架。在阅读了很多教程之后,这些教程总是在同一个java文件中创建JPanel和JButton等(在我的例子中是main.java)。

Just to test if it actually even did what i wanted, but when i pressed the button it didn't do anything. After that i tried working it out in my main.java where i actually created the frame with the JPanel in it. After reading alot of tutorials, which always created the JPanel and JButton etc. all in the same java file (which is in my case the main.java).

那么如何我是否检测到是否按下了登录按钮,然后让它处理JFrame并转到另一个方法,在其中我创建另一个包含信息的JFrame。

So how do i detect if the login button was pressed, and then make it dispose of the JFrame and move on to another Method in which i create another JFrame with information in it.

我希望我很清楚,如果不是,请告诉我。

I hope i am clear enough, if not please let me know.

编辑:
当我将测试代码更改为:user.equals(user它确实有效。但现在我需要它来处理Login框架并访问main.java中的另一个方法。如何在Login.java中的私有方法中实现此目的?

When i changed the test code to: user.equals("user") it did work. But now i need it to dispose the Login frame and access another method in my main.java. How can i achieve this from inside a private method in the Login.java?

提前致谢,

推荐答案


但现在我需要它来处理Login框架并访问我的main.java中的另一个方法
。如何在Login.java中的私有方法
内实现此目的?

But now i need it to dispose the Login frame and access another method in my main.java. How can i achieve this from inside a private method in the Login.java?

这里有一个设计问题。您无法调用任何框架的方法,因为 ActionListener 的范围仅限于登录面板。怎么解决这个?实现 c> ActionListener ,其可见性足以处置框架。

Here you have a design problem. You cannot call any frame's method because your ActionListener has its scope limited to Login panel. How to solve this? Implementing an ActionListener that has visibility enough to dispose the frame.

注意:尝试避免使用NetBeans GUI Builder(或任何GUI构建器)。这很容易,但是你想要做很多事情而不是自己动手做。你甚至可以写一个更干净的代码。但是有必要了解布局管理员

Note: try to avoid NetBeans GUI Builder (or any GUI builder). It's easy but you miss a lot of things than making it by your own hand. You can even write a cleaner code. But it's necessary learn about Layout Managers

代码示例:此示例说明了使用少于一半的代码行可以实现相同的事实。

Example of Code: this example illustrates the fact that you can achieve the same with less than half of lines of code.

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Demo {    

    private void initGUI(){        

        final JTextField textField = new JTextField(20);
        final JFrame frame = new JFrame("Login");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);        

        JButton button = new JButton("Accept");        
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if("user".equals(textField.getText())){
                    frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
                    // or simply frame.dispose()
                } else {
                    JOptionPane.showMessageDialog(null, "Wrong user! Keep trying.", "Login failed", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        JPanel login = new JPanel(new FlowLayout());
        login.add(new JLabel("User"));
        login.add(textField);
        login.add(button);

        frame.getContentPane().add(login);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }    

    public static void main(String[] args) {        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Demo().initGUI();
            }
        });
    }
}

这篇关于需要JButton事件的支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆