【发布时间】:2019-09-09 07:45:37
【问题描述】:
我编写了一个使用控制台进行用户输入的类。我正在尝试围绕它创建一个 GUI 来增强程序。结果,我创建了一个新的 GUI 类,我想用它来将值传递回现有的类。我花了几个小时在论坛上搜索,似乎找不到与我的具体问题相匹配的答案。
我找到的最接近的东西是pass radiobutton value that selected to another class ,我实际上使用了该课程的推荐。不过,它似乎“有时”有效。我的意思是当我第一次选择单选按钮“一个”时,什么也没有发生。然后我单击第二个单选按钮,没有任何反应(如预期的那样)。当我再次单击第一个单选按钮时,它会按预期将文本打印到控制台。我无法弄清楚为什么它在第一次点击时不起作用。其次,每次我单击第二个按钮并返回第一个按钮时,它打印的预期输出比之前的时间多 2 倍。
/// 单选按钮类
package views;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
import common.ButtonTester;
public class RadioButtons extends JFrame {
private JPanel contentPane;
private JRadioButton rdbtnOne, rdbtnTwo;
private ButtonGroup grp;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RadioButtons frame = new RadioButtons();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public RadioButtons() {
setTitle("Button Demo");
initComponents();
createEvents();
}
**/// Components**
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
rdbtnOne = new JRadioButton("One");
rdbtnTwo = new JRadioButton("Two");
grp = new ButtonGroup();
grp.add(rdbtnOne);
grp.add(rdbtnTwo);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(126)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(rdbtnTwo)
.addComponent(rdbtnOne))
.addContainerGap(189, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(87)
.addComponent(rdbtnOne)
.addGap(48)
.addComponent(rdbtnTwo)
.addContainerGap(70, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
**/// Event handlers**
private void createEvents() {
rdbtnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rdbtnOne.addActionListener(new ButtonTester());
}
});
}
}
/// ButtonTester 类
package common;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonTester implements ActionListener {
public static void main(String[] args) {
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello. I'm in the action Performed Method.");
}
}
我希望每次单击单选按钮 1 时,sysout 行都会执行一次。
【问题讨论】:
标签: java swing class object radio-button