我正在用netbeans编写一个程序,该程序允许用户导入其计算机规格,并且我有2个单选按钮,当您选择选项并按下display时,它会在文本区域中显示您的选择。我已经有了其他文本字段,该人员可以在其中输入信息,并将其显示在文本区域中,但是对于单选按钮,我将如何执行此操作。
private void displayActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
textarea.append("Processor: " + processorTextField.getText() + "\nGraphics Card: "
+ graphicsCardTextField.getText() + "\nRam: " + ramTextField.getText() + "\nHard Drive: " +
hardDriveTextField.getText() + "\nOperating System: " + operatingSystemTextField.getText()
+ "\nMonitor Size: " + monitorTextField.getText());
}
这是我已经拥有的代码,当按下显示按钮时,其他文本字段可以进入文本区域
如果已将JRadioButtons添加到ButtonGroup,则ButtonGroup可以通过调用getSelection()
它来从选定的JRadioButton中为您提供ButtonModel 。然后,您可以获取模型的actionCommand字符串(必须为JRadioButtons明确设置)。例如,假设一个名为ButtonGroup的ButtonGroup:
private void displayActionPerformed(java.awt.event.ActionEvent evt) {
// 1st get the ButtonModel for the selected radio button
ButtonModel buttonModel = buttonGroup.getSelection();
// if a selection has been made, then model isn't null
if (buttonModel != null) {
// again actionCommand needs to be set for each JRadioButton
String actionCommand = buttonModel.getActionCommand();
// TODO: use actionCommand String as needed
}
}
例如:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class RadioEg extends JPanel {
private static final String[] RADIO_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
public RadioEg() {
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
for (String radioText : RADIO_TEXTS) {
JRadioButton radioButton = new JRadioButton(radioText);
radioButton.setActionCommand(radioText); // set this!
radioPanel.add(radioButton); // add to JPanel
buttonGroup.add(radioButton); // add to button group
}
JPanel southPanel = new JPanel();
southPanel.add(new JButton(new AbstractAction("GetSelection") {
@Override
public void actionPerformed(ActionEvent e) {
ButtonModel buttonModel = buttonGroup.getSelection();
if (buttonModel != null) {
String actionCommand = buttonModel.getActionCommand();
System.out.println("Selected Button: " + actionCommand);
}
}
}));
setLayout(new BorderLayout());
add(radioPanel, BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("RadioEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RadioEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句