我应该如何让程序停止并等待某些事情

我应该如何让程序停止并等待某些事情

本文介绍了我应该如何让程序停止并等待某些事情?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有问题,目前正在尝试创建数据库系统的登录.我必须类:UserLogManagerMainWindow 和DatabaseConnectionFrame.我的程序是关于日志管理的.我想建立一个数据库连接:

got a problem here, trying to create a login to database system at the moment. I have to classes : UserLogManagerMainWindow and DatabaseConnectionFrame. My program is about log management. I want to make a database connection :

UserLogManagerMainWindow 类有一个连接到数据库"按钮,点击 DatabaseConnectionFrame 初始化并使用 jlabels 和 jtextfields 启动一个框架,在我输入我需要的所有内容后,我按下登录"按钮,然后我想要我的 UserLogManagerMainWindow课程继续从连接的数据库中压出日志.

UserLogManagerMainWindow class has a button "Connect to database", on it's click DatabaseConnectionFrame initialize and gets up a frame with jlabels and jtextfields, after I enter everything i need, i press "Login" button, after this I want that my UserLogManagerMainWindow class continues on pressenting the logs from connected database.

我已经写了一些关于它应该是什么样子的代码:关于我想说什么的逻辑"

I have written some code about how it supposed to look : "the logic about what am i trying to say"

            connectToDatabaseBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                DatabaseConnectionFrame dcf = new DatabaseConnectionFrame();
                dcf.setVisible(true);

                if(dcf.answer == true) {
                    importButtons(menuBar);
                    setJMenuBar(menuBar);
                    try {
                        DatabaseComm.getColumnNamesToPanel(model, titles);
                        projects = DatabaseComm.AddLogsToArrayReturnProjectNames(events);
                        DatabaseComm.fillDataToPanel(model, events, titles, row);
                        DatabaseComm.resizeColumnWidth(table);
                    } catch (SQLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }
                else {
                    System.out.println("not working");
                }

            }

        });

但是如果语句不起作用,我知道为什么.这就是为什么我要问如何使它工作?更有可能的是,线程是关键,但目前并不擅长.没有穿线有什么技巧吗?如果线程是唯一的方法,我可以得到一些帮助吗?

But if statement does not working, i know why. That's why i'm asking how to make it work? More likely, threading is the key, but not good at it at the moment. Any tips without threading? And if threading is the only way, may i get some help of it?

在下面提供 DatabaseConnectionFrame 类:

Giving DatabaseConnectionFrame class below either:

    package manager;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.JButton;

public class DatabaseConnectionFrame extends JFrame{

private JPanel contentPane;
private JTextField address;
private JPasswordField password;
private JTextField username;
private JButton btnLogin;
private JButton btnCancel;
private JLabel lblPort;
private JTextField port;

public boolean answer = false;

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

/**
 * Create the frame.
 */
public DatabaseConnectionFrame() {
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setSize(450,250);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GridBagLayout gbl_contentPane = new GridBagLayout();
    contentPane.setLayout(gbl_contentPane);

    JLabel lblDatabaseIpAddress = new JLabel("Database ip address:");
    GridBagConstraints gbc_lblDatabaseIpAddress = new GridBagConstraints();
    gbc_lblDatabaseIpAddress.anchor = GridBagConstraints.EAST;
    gbc_lblDatabaseIpAddress.insets = new Insets(0, 0, 5, 5);
    gbc_lblDatabaseIpAddress.gridx = 0;
    gbc_lblDatabaseIpAddress.gridy = 0;
    contentPane.add(lblDatabaseIpAddress, gbc_lblDatabaseIpAddress);

    address = new JTextField();
    GridBagConstraints gbc_textField = new GridBagConstraints();
    gbc_textField.insets = new Insets(0, 0, 5, 0);
    gbc_textField.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField.gridx = 1;
    gbc_textField.gridy = 0;
    contentPane.add(address, gbc_textField);
    address.setColumns(10);

    lblPort = new JLabel("Port");
    GridBagConstraints gbc_lblPort = new GridBagConstraints();
    gbc_lblPort.anchor = GridBagConstraints.EAST;
    gbc_lblPort.insets = new Insets(0, 0, 5, 5);
    gbc_lblPort.gridx = 0;
    gbc_lblPort.gridy = 1;
    contentPane.add(lblPort, gbc_lblPort);

    port = new JTextField();
    GridBagConstraints gbc_textField1 = new GridBagConstraints();
    gbc_textField1.insets = new Insets(0, 0, 5, 0);
    gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField1.gridx = 1;
    gbc_textField1.gridy = 1;
    contentPane.add(port, gbc_textField1);
    port.setColumns(10);

    JLabel lblUsername = new JLabel("Username:");
    lblUsername.setHorizontalAlignment(SwingConstants.CENTER);
    GridBagConstraints gbc_lblUsername = new GridBagConstraints();
    gbc_lblUsername.anchor = GridBagConstraints.EAST;
    gbc_lblUsername.insets = new Insets(0, 0, 5, 5);
    gbc_lblUsername.gridx = 0;
    gbc_lblUsername.gridy = 2;
    contentPane.add(lblUsername, gbc_lblUsername);

    username = new JTextField();
    GridBagConstraints gbc_textField_1 = new GridBagConstraints();
    gbc_textField_1.insets = new Insets(0, 0, 5, 0);
    gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
    gbc_textField_1.gridx = 1;
    gbc_textField_1.gridy = 2;
    contentPane.add(username, gbc_textField_1);
    username.setColumns(10);

    JLabel lblPassword = new JLabel("Password");
    GridBagConstraints gbc_lblPassword = new GridBagConstraints();
    gbc_lblPassword.anchor = GridBagConstraints.EAST;
    gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
    gbc_lblPassword.gridx = 0;
    gbc_lblPassword.gridy = 3;
    contentPane.add(lblPassword, gbc_lblPassword);

    password = new JPasswordField();
    GridBagConstraints gbc_passwordField = new GridBagConstraints();
    gbc_passwordField.insets = new Insets(0, 0, 5, 0);
    gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
    gbc_passwordField.gridx = 1;
    gbc_passwordField.gridy = 3;
    contentPane.add(password, gbc_passwordField);

    btnLogin = new JButton("Login");
    GridBagConstraints gbc_btnLogin = new GridBagConstraints();
    gbc_btnLogin.insets = new Insets(0, 0, 0, 5);
    gbc_btnLogin.gridx = 0;
    gbc_btnLogin.gridy = 4;
    contentPane.add(btnLogin, gbc_btnLogin);

    btnCancel = new JButton("Cancel");
    GridBagConstraints gbc_btnCancel = new GridBagConstraints();
    gbc_btnCancel.gridx = 1;
    gbc_btnCancel.gridy = 4;
    contentPane.add(btnCancel, gbc_btnCancel);




    btnCancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            dispose();

        }

    });

    btnLogin.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String dbAddress = address.getText();
            String dbPort = port.getText();
            String dbUsername = username.getText();
            char[] dbPassword = password.getPassword();

            if( dbAddress.isEmpty() || dbPort.isEmpty() || dbUsername.isEmpty() || dbPassword.length == 0) {
                JOptionPane.showMessageDialog(getParent(),
                        "All fields have to be filled!");
            }
            else {
                if(databaseValidation(dbAddress, dbPort, dbUsername, dbPassword)) {
                    JOptionPane.showMessageDialog(getParent(),
                            "Connected!");
                    answer = true;
                    setVisible(false);
                }
                else {
                    JOptionPane.showMessageDialog(getParent(),
                            "There was error connecting to the database!");
                    answer = false;
                }
            }
            System.out.println(answer);

        }

    });
}

public boolean databaseValidation(String address, String port, String username, char[] password) {

    String pw = String.valueOf(password);
    System.out.println(pw);
    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port +  "/logctrl?user=" + username + "&password=" + pw );
    } catch (SQLException e) {
        System.out.println("Error connecting to database!");
        return false;
    }
    System.out.println("Connected");
    return true;

}

}

推荐答案

如果你想等待用户输入,你有两个选择,你要么创建自己的观察者模式,它可以在未来的某个时刻被调用状态以某种方式发生变化,或者您使用对话框,这将在对话框可见时阻止代码执行,并等到它关闭

If you want to wait for the user input, you have two choices, you either make your own observer pattern which can be called at some point in the future when the state changes in some way or you use a dialog, which will block the codes execution at the point the dialog is made visible and will wait till it's closed

有关详细信息,请参阅如何使用对话框>

See How to use dialogs for details

import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

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

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            JButton btn = new JButton("Show the dialog");
            add(btn);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(TestPane.this), "I'm in charge now", true);
                    JButton btn = new JButton("Waiting");
                    btn.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            dialog.dispose();
                        }
                    });
                    dialog.add(btn);
                    dialog.pack();
                    dialog.setLocationRelativeTo(TestPane.this);
                    dialog.setVisible(true);

                    JOptionPane.showMessageDialog(TestPane.this, "You won't see this till the dialog is closed");
                }
            });
        }

    }
}

这篇关于我应该如何让程序停止并等待某些事情?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 20:01