简体   繁体   English

如何在按下按钮之前暂停方法?

[英]How do I pause a method until a button is pressed?

I am designing a software with multiple components - each with its own actionlistener. 我正在设计一个包含多个组件的软件 - 每个组件都有自己的actionlistener。 For an example, I have a JPanel with a cardlayout that holds 10 cards - each its own JPanel and purpose. 举个例子,我有一个带有cardlayout的JPanel,可以容纳10张卡片 - 每张卡片都有自己的JPanel和用途。

On one side, there are multiple buttons, IE Login, Logout, Settings, etc. 一方面,有多个按钮,IE登录,注销,设置等。

When I click Login, it will switch to the card using the Login() method to the Login JPanel object where I want it to wait for a button to click IE Login, New User, or Cancel before continuing the Login() method and setting the current user. 当我单击Login时,它将使用Login()方法切换到卡片到Login JPanel对象,我希望它在等待按钮单击IE登录,新用户或取消之后再继续Login()方法和设置当前用户。

Is there a method to pause the program until one of the buttons are clicked to retrieve the data from it? 是否有方法暂停程序,直到单击其中一个按钮从中检索数据? (Kind of like how JOptionPane.showInputMessage(null,"INPUT STRING") waits for you) (有点像JOptionPane.showInputMessage(null,“INPUT STRING”)如何等待你)

My Code is below: FRAME: 我的代码如下:FRAME:

/**
 * Frame design
 */


public class Frame extends JFrame{
JPanel LeftSide, UpperRightSide;
EmployeeAdder employAdd;
ArrayList<ServiceView> serviceViewers;
ChartViewer viewChart;
PayByView viewPayBy;
SettingsViewer viewSettings;
LoginViewer viewLogin;
CategoryView viewCategory;
ServiceAdder serviceAdd;
Directory directory;
Employee currentEmployee;
ChargeViewer viewCharge;
JButton Login, Logout, Settings;
CardLayout LeftCard,RightCard;
String currentCard,currentRightCard;
ButtonListen listen;
public static String CARDCAT = "Category View";
public static String CARDPAY = "Pay By";
public static String CARDCHART = "Chart View";
public static String CARDLOGIN = "Log-in View";
public static String CARDSERVICEADD = "Service Adder";

Frame(){
    listen = new ButtonListen();
    //-------Current Card--------------------
    currentCard = CARDCAT;
    currentRightCard = "CHARGE";
    //-----First Find Directory Folder-------
    startDirectory();
    //-----User Interface--------------------
    //-------Left Side-----------------------
    LeftSide = new JPanel();
    LeftCard = new CardLayout();
        LeftSide.setLayout(LeftCard);
        viewPayBy = new PayByView();
        viewLogin = new LoginViewer();
        viewChart = new ChartViewer();
        viewCategory = new CategoryView();
        employAdd = new EmployeeAdder();
        serviceAdd = new ServiceAdder();
        LeftSide.add(viewCategory,"CAT");
        LeftSide.add(viewChart, "CHA");
        LeftSide.add(viewLogin,"LOG");
        LeftSide.add(viewPayBy,"PAY");
        LeftSide.add(employAdd,"EMA");
        LeftSide.add(serviceAdd,"SEA");
        LeftCard.show(LeftSide, "CAT");
        viewCategory.setEnabled(false);
        LeftSide.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK),currentCard));
        serviceViewers = new ArrayList<ServiceView>();

    //--------Right Side---------------------
    JPanel RightSide = new JPanel();
        RightSide.setLayout(new BorderLayout());
        UpperRightSide = new JPanel();
        RightCard = new CardLayout();
        UpperRightSide.setLayout(RightCard);
            viewSettings = new SettingsViewer();
            viewCharge = new ChargeViewer();
            viewCharge.setEnabled(false);
            UpperRightSide.add(viewCharge,"CHARGE");
            UpperRightSide.add(viewSettings,"SETTINGS");
            UpperRightSide.setPreferredSize(new Dimension(350,500));
        RightSide.add(UpperRightSide,BorderLayout.NORTH);
        //--------Buttons at the bottom Panel---
        JPanel Buttons = new JPanel();
            Buttons.setLayout(new GridLayout(3,1));
            Login = new JButton("LOG-IN");
                Login.addActionListener(listen);
            Logout = new JButton("LOG OUT");
                Logout.addActionListener(listen);
            Settings = new JButton("Settings");
                Settings.addActionListener(listen);
            Buttons.add(Login);
            Buttons.add(Logout);
            Buttons.add(Settings);
            Buttons.setPreferredSize(new Dimension(350,150));
        RightSide.add(Buttons,BorderLayout.SOUTH);
        RightSide.setSize(new Dimension(400,200));
    //------Other Stuff--------------------------

    //-----add Panels----------------------------
        setLayout(new BorderLayout());
        add(LeftSide,BorderLayout.WEST);
        add(RightSide,BorderLayout.EAST);
}


private void Login(){
    LeftCard.show(LeftSide, "LOG");

    //----I WANT IT TO WAIT HERE FOR AN ACTION-------
    int clicked = viewLogin.getClicked();
        if (clicked==LoginViewer.NEWUSER){
            NewUser();
        }else if (clicked==LoginViewer.LOGIN){
            if (viewLogin.checkPassword()){
                currentEmployee = directory.getEmployee(viewLogin.getSelectedName());
                viewCategory.setEnabled(true);
                viewCharge.setEnabled(true);
                viewCharge.refreshName(currentEmployee.getName());
                LeftCard.show(LeftSide, "CAT");
            }
        }else if (clicked==LoginViewer.CANCEL){
            LeftCard.show(LeftSide, "CAT");
        }


}




public class ButtonListen implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        if (!viewLogin.isWaiting()){
        if (e.getSource()==Login){
            if (currentCard.equals(CARDLOGIN)){
                LeftCard.show(LeftSide,"CAT");
                currentCard = CARDCAT;

            }else{
                Login();
                currentCard = CARDLOGIN;
            }
        }else{
            //Don't change the screen
        }
        }

    }

}

}

My Code for LoginViewer: 我的LoginViewer代码:

public class LoginViewer extends JPanel{
JComboBox User;
JPasswordField passField;
JButton NewUser, Login, Cancel;
Hashtable<String,String> namespass; //names and password
private int clicked = -1;
ButtonListen listen;
public static int NEWUSER = 1;
public static int LOGIN = 0;
public static int CANCEL = 2;
boolean waiting;

LoginViewer(){
    waiting = false;
    //---------------------------------------
    setPreferredSize(new Dimension(100,100));
    listen = new ButtonListen();
    namespass = new Hashtable<String,String>();
    //----------Panel Design-------------------
    JPanel Center = new JPanel();
        Center.setLayout(new GridLayout(3,3));
    User = new JComboBox();
    passField = new JPasswordField();
    NewUser = new JButton("New User");
        NewUser.addActionListener(listen);
    Login = new JButton("Login");
        Login.addActionListener(listen);
    Cancel = new JButton("Cancel");
        Cancel.addActionListener(listen);
    Center.add(new JLabel("Choose User"));
    Center.add(User);
    Center.add(new JLabel(""));
    Center.add(new JLabel("Type Password"));
    Center.add(passField);
    Center.add(new JLabel(""));
    Center.add(Login);
    Center.add(NewUser);
    Center.add(Cancel);
    Center.setPreferredSize(new Dimension(300,300));
    Center.setMaximumSize(new Dimension(100,100));
    Center.setAlignmentX(CENTER_ALIGNMENT);
    setAlignmentX(CENTER_ALIGNMENT);
    setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
    add(Box.createHorizontalGlue());
    add(Center);
    add(Box.createHorizontalGlue());
}


public void uploadUserNames(Hashtable<String,String> names){
    namespass.clear();
    namespass.putAll(names);
    User.removeAllItems();
    Enumeration<String> name = names.keys();
    while (name.hasMoreElements()){
        User.addItem(name.nextElement());
    }
}

public boolean checkPassword(){
    boolean value = false;
    String key = User.getSelectedItem().toString();
    if (passField.getPassword().length==4){
        if (namespass.get(key).equals(String.valueOf(passField.getPassword()))){
            value = true;
        }
    }
    return value;
}

public String getSelectedName(){
    return User.getSelectedItem().toString();
}

public boolean isWaiting(){
    return waiting;
}

public int getClicked(){
    waiting = true;
    return clicked;
}

public class ButtonListen implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {

        waiting = false;
        if (e.getSource()==NewUser){
            clicked = 1;
        }else if (e.getSource()==Login){
            clicked = 0;
        }else if (e.getSource()==Cancel){
            clicked = 2;
        }

    }

}
}

Or is it easier to just use an actionlistener to listen to ALL of the objects' buttons? 或者只是使用actionlistener来收听所有对象的按钮更容易?

There are a LOT of buttons... 有很多按钮......

NOTE: Some of the methods are incomplete or test methods until I know how to make it work... 注意:在我知道如何使其工作之前,有些方法是不完整的或测试方法...

You don't want to use linear console-type code in a Swing GUI. 您不希望在Swing GUI中使用线性控制台类型代码。 Instead, with event-driven GUI programs you will want to have user interactions change a program's state, and then have the behavior of the program depend on the state. 相反,使用事件驱动的GUI程序,您将希望让用户交互更改程序的状态,然后让程序的行为取决于状态。 For instance, rather than have the login method pause, have it do some housekeeping -- change the state of the program to be ready to accept a login attempt -- and then where you plan to "wait", exit the login method. 例如,不要让登录方法暂停,让它做一些内务处理 - 更改程序的状态以准备接受登录尝试 - 然后在您计划“等待”的地方,退出登录方法。 Then have the rest of the code for logging in reside in the login button's ActionListener. 然后将其余用于登录的代码驻留在登录按钮的ActionListener中。

As an aside, you've posted a lot of code, 95% of it unrelated to your problem and thus only serving as a distraction to us and preventing us from reading the code and understanding the specifics of your problem. 顺便说一下,你发布了很多代码,95%的代码与你的问题无关,因此只会让我们分心,阻止我们阅读代码并理解问题的细节。 In the future, consider creating and posting an sscce , where you condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem for us. 在将来,考虑创建和发布一个sscce ,您可以将代码压缩到仍然编译的最小位,没有与您的问题无关的额外代码,但仍然为我们演示了您的问题。

the way the Swing framework works is that you already "wait" for everything to happen, and it only happens once the users triggers the action corresponding to your listener. Swing框架的工作方式是你已经“等待”所有事情发生,并且只有在用户触发与你的监听器相对应的动作时才会发生。

So yes, basically you only have to wait for buttons to be clicked. 所以是的,基本上你只需要等待点击按钮。

HOWEVER: Designing responsive GUIs means that you won't let your user wait 10 seconds on a frozen interface until you do yout 10000 calculations and 10 million SELECT statements. 但是:设计响应式GUI意味着在完成10000次计算和1000万次SELECT语句之前,不要让用户在冻结的接口上等待10秒。 Thus in case your action listeners (or whatever specific listeners you've got) have to perform heavy duty calculations, do them on a separate Thread , and inform the user if a task is done one way or another. 因此,如果您的动作侦听器(或您获得的任何特定侦听器)必须执行重载计算,请在单独的Thread上执行它们,并告知用户任务是以某种方式完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在循环中暂停直到按下按钮 - How to pause while loop until a button is pressed 我如何使用等待通知来停止在另一个类中等待按下按钮时暂停方法 - how do I use wait notify to stop pause a method while waiting on a button to be pressed in another class 如何创建一个jToggle按钮,该按钮在按下两次时会暂停? - How do I create a jToggle button that will pause when pressed twice? 如何更改按钮状态直到按下另一个按钮? - How do I change a button state until another button is pressed? 如何使Java程序暂停直到按下特定按钮? - How can I make my Java program pause until a specific button has been pressed? 如何暂停具有main()的程序,直到按下GUI中的按钮? - How to pause program having main() until a button from GUI is pressed? 在按下按钮之前,如何在Java中运行进程? - How do I run a process in Java until a button is pressed? 如何按下按钮直到方法结束 - How keep a button pressed until the method end 在按下按钮之前,如何让我的按钮出现在随机位置? - How do I make my buttons show up in random places until the button is pressed? 按下按钮直到用户点击EditText框,如何隐藏Android小键盘? - How do I hide Android keypad after a button is pressed until user taps an EditText box?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM