点击JButton时更改按钮文本

4
我创建了一个扩展了JDialog的类,其中包含一些复选框和三个按钮:接受、取消和全选。当用户点击“全选”时,每个复选框都应该被选中;再次点击,则所有复选框都应该取消选中状态。这方面已经运行良好,但我还希望按钮的文本在“全选”和“取消全选”之间切换。我在这方面遇到了麻烦,所以当用户点击按钮并且文本更改为“取消全选”时,按钮会消失。
我已将该类简化为以下形式:
    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;
    }
}

我看不出有什么问题。需要帮忙吗?


你的代码呢?你是怎么选择/取消选择复选框的?你在其他地方操纵了"allButton"变量吗? - Marcelo
我有一个复选框的监听器,但为了让代码更简单,我将其删除了。选择/取消选择功能正常,问题只出现在我尝试更改按钮文本时。而且,不,allButton没有在其他地方被操作。 - Roman Rdgz
3个回答

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

3

使用 event.getSource() 来访问被点击的按钮。


这与我处理的方式相同。编译通过,但问题仍然存在,按钮消失了。 - Roman Rdgz

2
另一种方法是使用实现了有趣方法的ButtonModel,例如: enter image description here enter image description here enter image description here
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TextAreaInButton {

    private JFrame frame = new JFrame("sssssssss");
    private JButton tip1Null = new JButton(" test button ");

    public TextAreaInButton() {
        Border line, raisedbevel, loweredbevel, title, empty;
        line = BorderFactory.createLineBorder(Color.black);
        raisedbevel = BorderFactory.createRaisedBevelBorder();
        loweredbevel = BorderFactory.createLoweredBevelBorder();
        title = BorderFactory.createTitledBorder("");
        empty = BorderFactory.createEmptyBorder(1, 1, 1, 1);
        final Border compound;
        Color crl = (Color.blue);
        compound = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl));
        Color crl1 = (Color.red);
        final Border compound1;
        compound1 = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl1));
        Color crl2 = (Color.black);
        final Border compound2;
        compound2 = BorderFactory.createCompoundBorder(empty, new OldRoundedBorderLine(crl2));
        tip1Null.setFont(new Font("Serif", Font.BOLD, 14));
        tip1Null.setForeground(Color.darkGray);
        tip1Null.setPreferredSize(new Dimension(50, 30));
        tip1Null.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });
        tip1Null.setBorderPainted(true);
        tip1Null.setFocusPainted(false);
        tip1Null.setBorder(compound);
        tip1Null.setHorizontalTextPosition(SwingConstants.CENTER);
        tip1Null.setVerticalTextPosition(SwingConstants.BOTTOM);

        tip1Null.getModel().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                ButtonModel model = (ButtonModel) e.getSource();
                if (model.isRollover()) {
                    tip1Null.setBorder(compound1);
                } else {
                    tip1Null.setBorder(compound);
                }
                if (model.isPressed()) {
                    tip1Null.setBorder(compound2);
                    String btnText = (tip1Null.getText());
                    if (btnText.equals("Selected")) {
                        tip1Null.setText("Un_Selected");
                    } else {
                        tip1Null.setText("Selected");
                    }
                }
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(tip1Null, BorderLayout.CENTER);
        frame.setLocation(150, 150);
        frame.setPreferredSize(new Dimension(310, 75));
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                TextAreaInButton taib = new TextAreaInButton();
            }
        });
    }
}

class OldRoundedBorderLine extends AbstractBorder {

    private final static int MARGIN = 5;
    private static final long serialVersionUID = 1L;
    private Color color;

    OldRoundedBorderLine(Color clr) {
        color = clr;
    }

    public void setColor(Color clr) {
        color = clr;
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        ((Graphics2D) g).setRenderingHint(
                RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(color);
        g.drawRoundRect(x, y, width, height, MARGIN, MARGIN);
    }

    @Override
    public Insets getBorderInsets(Component c) {
        return new Insets(MARGIN, MARGIN, MARGIN, MARGIN);
    }

    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.left = MARGIN;
        insets.top = MARGIN;
        insets.right = MARGIN;
        insets.bottom = MARGIN;
        return insets;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接