我正在对我的HOMEWORK(请不要为我做我的工作)。我已经有95%完成了。尽管如此,我仍然遇到了麻烦。我需要在JTextArea中显示选定的性别。我必须使用JRadioButton进行性别选择。显示文本从选定的JRadioButton到JTextArea
据我所知,JRadioButtons的工作方式不同。我设置了动作监听器和助记符。我想我在这里搞乱了。似乎我可能需要使用整个团队来设置和行动lister。
任何帮助,非常感谢。
这里是我有我的代码(即我不认为需要这样其他人不能复制粘贴功课减去部分):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
public class LuisRamosHW3 extends JFrame {
private JLabel WelcomeMessage;
private JRadioButton jrbMale = new JRadioButton("Male");
private JRadioButton jrbFemale = new JRadioButton("Female");
public LuisRamosHW3(){
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 30));
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(2,1));
jpRadioButtons.add(jrbMale);
jpRadioButtons.add(jrbFemale);
add(jpRadioButtons, BorderLayout.AFTER_LAST_LINE);
ButtonGroup gender = new ButtonGroup();
gender.add(jrbMale);
jrbMale.setMnemonic(KeyEvent.VK_B);
jrbMale.setActionCommand("Male");
gender.add(jrbFemale);
jrbFemale.setMnemonic(KeyEvent.VK_B);
jrbFemale.setActionCommand("Female");
//Set defaulted selection to "male"
jrbMale.setSelected(true);
//Create Welcome button
JButton Welcome = new JButton("Submit");
add(Welcome);
Welcome.addActionListener(new SubmitListener());
WelcomeMessage = (new JLabel(" "));
add(WelcomeMessage);
}
class SubmitListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
String FirstName = jtfFirstName.getText();
String FamName = jtfLastName.getText();
Object StateBirth = jcbStates.getSelectedItem();
String Gender = gender.getActionCommand(); /*I have tried different
variations the best I do is get one selection to print to the text area*/
WelcomeMessage.setText("Welcome, " + FirstName + " " + FamName + " a "
+ gender.getActionCommmand + " born in " + StateBirth);
}
}
} /*Same thing with the printing, I have tried different combinations and just can't seem to figure it out*/
不知道,但我想应该是这样_getText JRadioButton类的()_或类似的方法。您可能需要使用JRadioButton的动作侦听器,如_onSelectListener_。最后用提取的字符串设置JTextField。根据你的要求,我只告诉你该做什么和怎么做,而不是完全说出正确的东西(其实我也不知道应该做什么)。这应该是正确的流程。祝你好运 – Nabin 2014-09-21 16:54:41
@Nabin:不,不要在JRadioButton上使用ActionListener,因为重要的选择时间是按下提交按钮的时间。原始的海报有它的权利 - 使用ButtonGroup对象,但他首先需要使其可见,给它的类作用域。 – 2014-09-21 17:06:20