简体   繁体   English

如何在Java中禁用GUI按钮

[英]How to Disable GUI Button in Java

so I have this small piece of code for my GUI: 所以我的GUI有一小段代码:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;
    private static boolean btn1Clicked = false;
    private static boolean btn2Clicked = false;
    private static boolean btn3Clicked = false;
    private static boolean btn4Clicked = false;

    //Create the frame
    public IPGUI() 
    {
        //Sets frame properties
        setTitle("IP Extractor");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 250, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        //Creates new JPanel with boxlayout
        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        //////////////////New Button//////////////////

        JButton btnConvertDocuments = new JButton("1. Convert Documents");
        btnConvertDocuments.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnConvertDocuments.setMaximumSize(new Dimension(160, 0));
        btnConvertDocuments.setPreferredSize(new Dimension(0, 50));

        panel.add(btnConvertDocuments);

        btnConvertDocuments.setActionCommand("w");
        btnConvertDocuments.addActionListener((ActionListener) this);

        if (btn1Clicked == true)
        {
            btnConvertDocuments.setEnabled(false);
        }

        JSeparator separator_3 = new JSeparator();
        panel.add(separator_3);

        //////////////////New Button//////////////////

        JButton btnExtractImages = new JButton("2. Extract Images");
        btnExtractImages.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnExtractImages.setMaximumSize(new Dimension(160, 0));
        btnExtractImages.setPreferredSize(new Dimension(0, 50));

        panel.add(btnExtractImages);

        btnExtractImages.setActionCommand("x");
        btnExtractImages.addActionListener((ActionListener) this);

         if (btn2Clicked == true)
         {
             btnExtractImages.setEnabled(false);
         }

        JSeparator separator_2 = new JSeparator();
        panel.add(separator_2);

        //////////////////New Button//////////////////

        JButton btnParseRIDValues = new JButton("3. Parse rId Values");
        btnParseRIDValues.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnParseRIDValues.setMaximumSize(new Dimension(160, 0));
        btnParseRIDValues.setPreferredSize(new Dimension(0, 50));

        panel.add(btnParseRIDValues);

        btnParseRIDValues.setActionCommand("y");
        btnParseRIDValues.addActionListener((ActionListener) this);

        if (btn3Clicked == true)
        {
            btnParseRIDValues.setEnabled(false);
        }

        JSeparator separator_1 = new JSeparator();
        panel.add(separator_1);

        //////////////////New Button//////////////////

        JButton btnParseImageInfo = new JButton("4. Parse Image Info.");
        btnParseImageInfo.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnParseImageInfo.setMaximumSize(new Dimension(160, 0));
        btnParseImageInfo.setPreferredSize(new Dimension(0, 50));

        panel.add(btnParseImageInfo);

        btnParseImageInfo.setActionCommand("z");
        btnParseImageInfo.addActionListener((ActionListener) this);

        if (btn4Clicked == true)
        {
            btnParseImageInfo.setEnabled(false);
        }
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btn1Clicked = true;
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btn2Clicked = true;
        }
        else if (command.equals("y")) 
        {
            XMLIDParser xip = new XMLIDParser();
            btn3Clicked = true;
        }
        else if (command.equals("z")) 
        {
            XMLTagParser xtp = new XMLTagParser();
            btn4Clicked = true;
        }
    }    
}

The part I want to focus specifically, is this conditional: 我想特别关注的部分是有条件的:

 if (btn1Clicked == true)
        {
            btnConvertDocuments.setEnabled(false);
        }

So my belief is that what that command should do is this: once the button is clicked and the action performed method is called, btnClicked should be set to true, thus that button should then become disabled. 所以我的信念是,该命令应该做的是:一旦点击按钮并调用动作执行方法,btnClicked应该设置为true,因此该按钮应该被禁用。

Can someone explain where am I going wrong here, or if I have the right idea here? 有人可以解释我在哪里出错,或者我在这里有正确的想法吗? Thank you in advance for any input! 提前感谢您的任何输入!

You should put the statement btnConvertDocuments.setEnabled(false); 你应该把语句btnConvertDocuments.setEnabled(false); in the actionPerformed(ActionEvent event) method. actionPerformed(ActionEvent event)方法中。 Your conditional above only get call once in the constructor when IPGUI object is being instantiated. 上面的条件只在实例化IPGUI对象时在构造函数中调用一次。

if (command.equals("w")) {
    FileConverter fc = new FileConverter();
    btn1Clicked = true;
    btnConvertDocuments.setEnabled(false);
}

really that not possible to disable JComponent(s) if output to the GUI is invoked from Listener , in all of cases, all events are inside EDT including setEnabled/setVisible , 实际上,如果从Listener调用GUI的输出,则无法禁用JComponent(s) ,在所有情况下,所有事件都在EDT中,包括setEnabled/setVisible

JComponent(s) is/are disabled/visible if all Events in EDT ends, 如果EDT中的所有事件结束,则JComponent(s)被禁用/可见

there are there ways 有办法

1/ safiest way would be look for GlassPane , which prevents after all MouseEvents (not KeyEvents ) best code around is by camickr's 1 /最安全的方式是寻找GlassPane ,它可以防止所有MouseEvents (不是KeyEvents )最好的代码是由camickr's

2/ use multithreading with SwingWorker for separate and delay concrete event(s), Action from JComponent -> disable JComponent(s) in GUI -> then required Action , but there (if is possible to adds) you have to identify all actions by using myAction#putProperty("String","String") 2 /使用SwingWorker多线程处理单独和延迟的具体事件, Action from JComponent -> disable JComponent(s) in GUI -> then required Action ,但是那里(如果可以添加)你必须通过使用myAction#putProperty("String","String")

3/ put Enabled/Visible to the invokeLater() and all Action from Listener must be wrapped into invokeAndWait() 3 /对invokeLater() Enabled/Visible ,并且必须将来自Listener的所有Action包装到invokeAndWait()

4/ inside Runnable()#Thread 4 /在Runnable()#Thread内部

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. 而不是使用布尔值,为什么不在单击时将按钮设置为false,因此您可以在actionPerformed方法中执行此操作。 Its more efficient.. 它效率更高..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

Once you've created the frame the part of the code with your conditional isn't going to get entered. 一旦你创建了框架,你的条件部分代码就不会被输入。 To put it another way, at the time you execute the test if (btn1Clicked == true) , the button has not only not been clicked yet, it hasn't even been displayed to the user. 换句话说,当你执行测试if (btn1Clicked == true) ,按钮不仅没有被点击,甚至还没有显示给用户。

Lose the booleans and move the line with the btnConvertDocuments.setEnabled(false) into your actionListener. 丢失布尔值并将带有btnConvertDocuments.setEnabled(false)的行移动到actionListener中。 Make the buttons instance variables, do not make them static variables. 使按钮实例变量,不要使它们成为静态变量。 (Alternatively you could keep the buttons as local variables and assign each of them their own anonymous inner class listener.) (或者,您可以将按钮保留为局部变量,并为每个按钮分配他们自己的匿名内部类侦听器。)

You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all. 您可以使用按钮启用创建框架,进行一些测试以查看btn1Cliked是否为真,这就是全部。

Then you have the actionPerformed method that does nothing with your button. 然后你有actionPerformed方法,它对你的按钮什么都不做。 So, if you don't have any action related, your button status will never be evaluated again. 因此,如果您没有任何相关操作,则永远不会再次评估您的按钮状态。

Is there a reason you are not doing something like: 有没有理由你不做这样的事情:

public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    public IPGUI() 
    {
        ...

        btnConvertDocuments = new JButton("1. Convert Documents");

        ...

        btnExtractImages = new JButton("2. Extract Images");

        ...

        //etc.
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled( false );
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled( false );
        }

        // etc.
    }    
}

The if statement with your disabling code won't get called unless you keep calling the IPGUI constructor. 除非您继续调用IPGUI构造函数,否则不会调用带有禁用代码的if语句。

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    //Create the frame
    public IPGUI() 
    {
        //Sets frame properties
        setTitle("IP Extractor");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 250, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        //Creates new JPanel with boxlayout
        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        //////////////////New Button//////////////////

        JButton btnConvertDocuments = new JButton("1. Convert Documents");
        btnConvertDocuments.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnConvertDocuments.setMaximumSize(new Dimension(160, 0));
        btnConvertDocuments.setPreferredSize(new Dimension(0, 50));

        panel.add(btnConvertDocuments);

        btnConvertDocuments.setActionCommand("w");
        btnConvertDocuments.addActionListener((ActionListener) this);

        JSeparator separator_3 = new JSeparator();
        panel.add(separator_3);

        //////////////////New Button//////////////////

        btnExtractImages = new JButton("2. Extract Images");
        btnExtractImages.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnExtractImages.setMaximumSize(new Dimension(160, 0));
        btnExtractImages.setPreferredSize(new Dimension(0, 50));

        panel.add(btnExtractImages);

        btnExtractImages.setActionCommand("x");
        btnExtractImages.addActionListener((ActionListener) this);

        JSeparator separator_2 = new JSeparator();
        panel.add(separator_2);

        //////////////////New Button//////////////////

        JButton btnParseRIDValues = new JButton("3. Parse rId Values");
        btnParseRIDValues.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnParseRIDValues.setMaximumSize(new Dimension(160, 0));
        btnParseRIDValues.setPreferredSize(new Dimension(0, 50));

        panel.add(btnParseRIDValues);

        btnParseRIDValues.setActionCommand("y");
        btnParseRIDValues.addActionListener((ActionListener) this);

        JSeparator separator_1 = new JSeparator();
        panel.add(separator_1);

        //////////////////New Button//////////////////

        JButton btnParseImageInfo = new JButton("4. Parse Image Info.");
        btnParseImageInfo.setAlignmentX(Component.CENTER_ALIGNMENT);
        btnParseImageInfo.setMaximumSize(new Dimension(160, 0));
        btnParseImageInfo.setPreferredSize(new Dimension(0, 50));

        panel.add(btnParseImageInfo);

        btnParseImageInfo.setActionCommand("z");
        btnParseImageInfo.addActionListener((ActionListener) this);
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled(false);
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled(false);
        }
        else if (command.equals("y")) 
        {
            XMLIDParser xip = new XMLIDParser();
            btnParseRIDValues.setEnabled(false);
        }
        else if (command.equals("z")) 
        {
            XMLTagParser xtp = new XMLTagParser();
            btnParseImageInfo.setEnabled(false);        
        }
    }


}

Here is the solution I came up with thanks to everyone's help. 这是我提出的解决方案,感谢大家的帮助。 Thank you again everyone for your input, really appreciate it! 再次感谢大家的意见,真的很感激!

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. 而不是使用布尔值,为什么不在单击时将按钮设置为false,因此您可以在actionPerformed方法中执行此操作。 Its more efficient.. 它效率更高..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM