gpt4 book ai didi

java - 单击时更改 JButton 文本

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:41:37 25 4
gpt4 key购买 nike

我创建了一个扩展 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;
}
}

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

最佳答案

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

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

关于java - 单击时更改 JButton 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9412620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com