gpt4 book ai didi

java - 未选择单选按钮时调用 ActionEvent

转载 作者:行者123 更新时间:2023-12-01 12:09:22 26 4
gpt4 key购买 nike

我注意到,即使指定条件语句,ActionEvent 仍会在我的 JRadioButtonMenuItem 组中触发:

if(!button.isSelected())
//Do stuff
<小时/>
defaultTheme = new JRadioButtonMenuItem("Default theme");
defaultTheme.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!defaultTheme.isSelected())
System.out.println("temp");
}
});
<小时/>

我的设置菜单中有多个主题选项,但是如果已经选择了一个说(说默认),并且已经选择了默认菜单并且我不想执行任何冗余代码用户单击已选择的单选按钮。

最佳答案

ActionListener 会在按钮被“操作”(单击、按下等)时告诉您,但这并不总是会改变其状态。相反,您可以将 ItemListener 附加到按钮模型,这将更准确地告诉您按钮的实际状态何时发生变化,例如...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ButtonTest {

public static void main(String[] args) {
new ButtonTest();
}

public ButtonTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;

ButtonGroup bg = new ButtonGroup();
final JRadioButton bananas = new JRadioButton("Bananas");
final JRadioButton apples = new JRadioButton("Apples");
bg.add(bananas);
bg.add(apples);

bananas.getModel().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Bananas " + bananas.isSelected());
}
});
apples.getModel().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Apples " + apples.isSelected());
}
});

add(bananas, gbc);
add(apples, gbc);

}

}

}

关于java - 未选择单选按钮时调用 ActionEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27347929/

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