小编典典

单击时更改JButton文本

java

我创建了一个扩展JDialog的类,其中有一些复选框和3个按钮:接受,取消和全选。

当用户单击全选时,应选中每个复选框,如果再次单击,则应取消选中每个复选框。效果很好,但我还希望按钮的文本在“全选”和“全选”之间切换。我在这里遇到了麻烦,因此当用户单击按钮并将文本更改为“取消全选”时,该按钮消失了。

我在这里将类简化为最简单的形式:

    public class NodeSelectionCheckBoxJDialog extends JDialog {
    public enum Options {ACEPT, CANCEL};
    private Options selectedOption;
    private JButton allButton;
    private boolean allCheckBoxesSelected;
    private JButton aceptButton;

    public NodeSelectionCheckBoxJDialog(){
        super(MainFrame.getInstance());
        this.setTitle("Select nodes to apply");
        this.setModal(true);

        selectedOption = Options.CANCEL;
        nodeCheckBoxesSet = new HashSet<NodeCheckBox>();

        try {
            initComponents();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    private void initComponents() throws Exception {
        this.getContentPane().add(createActionButtons(), BorderLayout.SOUTH);
    }

    private Component createActionButtons() {
        JPanel buttonsPanel = new JPanel();
        allCheckBoxesSelected = false;
        aceptButton = new JButton("Accept");
        aceptButton.setEnabled(false);
        buttonsPanel.add(aceptButton);
        aceptButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                selectedOption = Options.ACEPT;
                dispose();
            }
        });

        JButton cancelButton = new JButton("Cancel");
        buttonsPanel.add(cancelButton);
        cancelButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                selectedOption = Options.CANCEL;
                dispose();
            }
        });

        allButton = new JButton("Select all");
        buttonsPanel.add(allButton);
        allButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(allCheckBoxesSelected){
                    allCheckBoxesSelected = false;
                    allButton.setText("Select all");
                } else {
                    allCheckBoxesSelected = true;
                    allButton.setText("Unselect all");
                }
            }
        });

        return buttonsPanel;
    }
}

我看不出有什么问题。有什么帮助吗?


阅读 216

收藏
2020-11-01

共1个答案

小编典典

该按钮不会消失,只是变得太宽而无法容纳在窗口中。更改按钮标签时只需重绘组件即可:

@Override
public void actionPerformed(ActionEvent e) {
    if(allCheckBoxesSelected){
        allCheckBoxesSelected = false;
        allButton.setText("Select all");
    } else {
        allCheckBoxesSelected = true;
        allButton.setText("Unselect all");
        NodeSelectionCheckBoxJDialog.this.pack();
    }
}
2020-11-01