JAVA 在用户未选择文件时禁用按钮

JAVA disable button while the user has not selected a file

我想在用户没有选择两个 PDF 时禁用我的合并按钮。 我该怎么做呢?我试图做一个 while 循环来检查 file1file2 是否为空,但循环没有终止。

package pdfMerge;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFMergerUtility;

import java.awt.event.*;


public class pdfMerger extends JFrame {
    private static final String ActionEvent = null;
    private JButton choose1, choose2, mergeButton;
    private JFileChooser fileChooser1, fileChooser2;
    private JPanel contentsPane;
    private int returnValue1, returnValue2;
    private File file1, file2;
    private String fileName1, fileName2;
    private boolean valid;


    public pdfMerger(){
        super("PDF Merger");
        setLayout(new BorderLayout());
        setSize(500, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        addComponents();
        addAction();
        setVisible(true);

    }

    public void addComponents(){

        contentsPane = new JPanel(new GridLayout(0, 3));
        add(contentsPane, BorderLayout.SOUTH);

        choose1 = new JButton("Choose 1st pdf");
        choose2 = new JButton("Choose 2nd pdf");

        mergeButton = new JButton("Merge");



        fileChooser1 = new JFileChooser();
        fileChooser2 = new JFileChooser();

        contentsPane.add(choose1);
        contentsPane.add(choose2);
        contentsPane.add(mergeButton);

    }

    public void addAction(){
        choose1.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent event){

                                if (event.getSource() == choose1){
                                    returnValue1 = fileChooser1.showOpenDialog(null);
                                    if (returnValue1 == JFileChooser.APPROVE_OPTION){
                                        file1 = fileChooser1.getSelectedFile();
                                        fileName1 = file1.toString();
                                        fileName1 = fileName1.replace("\", "\\");
                                        System.out.println(fileName1);


                                }
                            }
                        }
                    }
        );
        choose2.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent event){
                                if (event.getSource() == choose2){
                                    returnValue2 = fileChooser2.showOpenDialog(null);
                                    if (returnValue2 == JFileChooser.APPROVE_OPTION){
                                        file2 = fileChooser2.getSelectedFile();
                                        fileName2 = file2.toString();
                                        fileName2 = fileName2.replace("\", "\\");
                                        System.out.println(fileName2);
                                }
                            }
                        }
                    }
        );

        mergeButton.addActionListener(
                new ActionListener(){


                    public void actionPerformed(ActionEvent event){


                        PDFMergerUtility ut = new PDFMergerUtility();
                        ut.addSource(fileName1);
                        ut.addSource(fileName2);
                        ut.setDestinationFileName("C:\Users\Shaheedul\Desktop\MergedPDF.pdf");
                        try {
                            ut.mergeDocuments();
                        } catch (Exception error){
                            System.out.println("Something went wrong!");
                        }
                    }
                }
        );


    }
    }

简单:将 mergeButton 或其 Action 设置为禁用以开始:

mergeButton.setEnabled(false);

然后在您的文件选择按钮的动作侦听器中,如果已选择 2 个文件,则将 mergeButton 设置为启用。

例如注意标有 // !!

的主要评论
// !! class names should begin with upper case letter
public class PdfMerger extends JFrame {
    // ...
    private JButton choose1, choose2, mergeButton;
    // ...

    public PdfMerger() {
        super("PDF Merger");
        setLayout(new BorderLayout());
        setSize(500, 500); // advise against this
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        addComponents();
        addAction();
        setVisible(true);

        // !!
        mergeButton.setEnabled(false);
    }

    // ...

    public void addAction() {
        choose1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                if (event.getSource() == choose1) {
                    returnValue1 = fileChooser1.showOpenDialog(null);
                    if (returnValue1 == JFileChooser.APPROVE_OPTION) {
                        file1 = fileChooser1.getSelectedFile();
                        fileName1 = file1.toString();
                        fileName1 = fileName1.replace("\", "\\");
                        System.out.println(fileName1);

                        // !! added
                        mergeButton.setEnabled(bothFilesChosen());
                    }
                }
            }
        });
        choose2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                if (event.getSource() == choose2) {
                    returnValue2 = fileChooser2.showOpenDialog(null);
                    if (returnValue2 == JFileChooser.APPROVE_OPTION) {
                        file2 = fileChooser2.getSelectedFile();
                        fileName2 = file2.toString();
                        fileName2 = fileName2.replace("\", "\\");
                        System.out.println(fileName2);

                        // !! added
                        mergeButton.setEnabled(bothFilesChosen());
                    }
                }
            }
        });

        // ....

    }

    // !!
    private boolean bothFilesChosen() {
        return (file1 != null && file1.exists() && file2 != null && file2.exists());
    }
}

好吧,当您有一个选择按钮时,您可能应该在 Swing 组件中显示所选文件,以便用户可以直观地了解已选择的文件。如果您不显示该值,用户如何知道他们点击了两个按钮?此外,如果 "Merge" 按钮被禁用,用户如何知道单击哪个 "select" 按钮以启用合并按钮?

因此,在这种情况下,您可以使用不可编辑的文本字段。然后,您可以向每个文本字段添加一个 DocumentListener。每当在任一字段中更改文本时,您都会检查 "Merge" 按钮是否应为 enabled/disabled.

下面是这种方法的一个例子:

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;

public class DataEntered implements DocumentListener
{
    private JButton button;
    private List<JTextField> textFields = new ArrayList<JTextField>();

    public DataEntered(JButton button)
    {
        this.button = button;
    }

    public void addTextField(JTextField textField)
    {
        textFields.add( textField );
        textField.getDocument().addDocumentListener( this );
    }

    public boolean isDataEntered()
    {
        for (JTextField textField : textFields)
        {
            if (textField.getText().trim().length() == 0)
                return false;
        }

        return true;
    }

    @Override
    public void insertUpdate(DocumentEvent e)
    {
        checkData();
    }

    @Override
    public void removeUpdate(DocumentEvent e)
    {
        checkData();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {}

    private void checkData()
    {
        button.setEnabled( isDataEntered() );
    }

    private static void createAndShowUI()
    {
        JButton submit = new JButton( "Submit" );
        submit.setEnabled( false );

        JTextField textField1 = new JTextField(10);
        JTextField textField2 = new JTextField(10);

        DataEntered de = new DataEntered( submit );
        de.addTextField( textField1 );
        de.addTextField( textField2 );

        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.WEST);
        frame.add(textField2, BorderLayout.EAST);
        frame.add(submit, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}