Java-将选择的一个单选按钮的值传递到另一框架

标签 java swing jradiobutton

是否有任何代码可以用来将所选单选按钮的值传递到另一个框架?

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class bookBatman extends JFrame implements ActionListener {

    private JLabel jlbName, jlbTime, jlbPic, jlbDate, jlbDescription, jlbAuthor, jlbDateProduce, jlbDirector, jlbActor, jlbRate, jlbNoOfTicket, jlbPrice, jlbTotal;
    private JTextField jtfNoOfTicket;
    private JRadioButton jr1, jr2, jr3, jr4, jr5, jr6, jr7, jr8, jr9, jr10;
    private JButton jTotal, jBook, jCancel;

    Font f = new Font("Times",Font.BOLD,30);

    public bookBatman () {


        setLayout(null); //set LayoutManager

        // initialized the label
        jlbName = new JLabel ("Batman The Dark Knight");
        jlbTime = new JLabel ("Time :");
        jlbPrice = new JLabel ("RM 9.00");
        jlbPic = new JLabel ();
        jlbPic.setIcon(new ImageIcon("C:\\Users\\User\\Desktop\\OOP project\\img\\icon\\Batman.jpg"));
        jlbTotal = new JLabel (" Total : RM 9.00");



        // add all the label on the frame
        add(jlbName);
        add(jlbPic);
        add(jlbTime);
        add(jlbPrice);
        add(jlbTotal);


        // set all the label positions
        jlbName.setBounds(85, 78, 300, 18); //(int x, int y, int width, int height)
        jlbPic.setBounds(74, 101, 180, 288);
        jlbTime.setBounds(74, 400, 60, 18);
        jlbPrice.setBounds (270, 477, 60, 18);
        jlbTotal.setBounds (339, 475, 300, 22);


        // initialized the textfield
        jlbAuthor = new JLabel ("Directed by Christopher Nolan");
        jlbDateProduce = new JLabel ("Date : 17 July 2008");
        jlbDirector = new JLabel ("Author : Jonathan Nolan, Christopher Nolan");
        jlbActor = new JLabel ("Main Actor : Christian Bale");
        jlbRate = new JLabel ("Movie Rate : 13 PG (Parental Guidance)");
        jlbNoOfTicket = new JLabel ("Number of Ticket :");


        // add all the textfield on the frame
        add(jlbAuthor);
        add(jlbDateProduce);
        add(jlbDirector);
        add(jlbActor);
        add(jlbRate);
        add(jlbNoOfTicket);


        // set the textfield position
        jlbAuthor.setBounds (273, 102, 300, 18);
        jlbDateProduce.setBounds (273, 132, 300, 18);
        jlbDirector.setBounds (273, 162, 300, 18);
        jlbActor.setBounds (273, 192, 300, 18);
        jlbRate.setBounds (273, 222, 300, 18);
        jlbNoOfTicket.setBounds (77, 478, 150, 18);


        // initialize the Radio Button
        jr1 = new JRadioButton ("11.40 AM");
        jr2 = new JRadioButton ("12.00 PM");
        jr3 = new JRadioButton ("1.40 PM");
        jr4 = new JRadioButton ("3.40 PM");
        jr5 = new JRadioButton ("5.40 PM");
        jr6 = new JRadioButton ("7.00 PM");
        jr7 = new JRadioButton ("9.00 PM");
        jr8 = new JRadioButton ("10.40 PM");
        jr9 = new JRadioButton ("11.40 PM");
        jr10 = new JRadioButton ("12.40 AM");


        // add all the radion button
        add(jr1);
        add(jr2);
        add(jr3);
        add(jr4);
        add(jr5);
        add(jr6);
        add(jr7);
        add(jr8);
        add(jr9);
        add(jr10);


        // set the radion button positions
        jr1.setBounds (75, 423, 100, 24);
        jr2.setBounds (172, 423, 100, 24);
        jr3.setBounds (269, 423, 100, 24);
        jr4.setBounds (366, 423, 100, 24);
        jr5.setBounds (463, 423, 100, 24);
        jr6.setBounds (75, 447, 100, 24);
        jr7.setBounds (172, 447, 100, 24);
        jr8.setBounds (269, 447, 100, 24);
        jr9.setBounds (366, 447, 100, 24);
        jr10.setBounds (463, 447, 100, 24);


        // group the button
        ButtonGroup group = new ButtonGroup ();
        group.add(jr1);
        group.add(jr2);
        group.add(jr3);
        group.add(jr4);
        group.add(jr5);
        group.add(jr6);
        group.add(jr7);
        group.add(jr8);
        group.add(jr9);
        group.add(jr10);

        jr1.setActionCommand("radio1"); // for ButtonGroup
        String sel = group.getSelection().getActionCommand();


        // initialize all the button
        jTotal = new JButton ("Total");
        jBook = new JButton ("Book Now");
        jCancel = new JButton ("Cancel");


        // add all the button
        add (jTotal);
        add (jBook);
        add (jCancel);


        // set the button positions
        jTotal.setBounds (191, 519, 83, 28);
        jBook.setBounds (285, 519, 93, 28);
        jCancel.setBounds (389, 519, 83, 28);


        // add actionlistener
        jTotal.addActionListener (this);
        jBook.addActionListener (this);
        jCancel.addActionListener (this);


        // initialize all text field
        jtfNoOfTicket = new JTextField (15);

        // add all the text field
        add (jtfNoOfTicket);


        // set the text field positions
        jtfNoOfTicket.setBounds (200, 477, 56, 22);
    }



    public void actionPerformed(ActionEvent e){
                if((e.getSource() == jTotal)) {

                    double price = 12.00;
                    double number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
                    double total = 0.0;
                    total = price * number;
                    jlbTotal.setText(" Total : RM" + total +"0");
                }

                if((e.getSource() == jBook)) {


                    String name = jlbName.getText ();
                    String date = jlbDateProduce.getText ();
                    String time = jr1.getText ();
                    int number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
                    String total = jlbTotal.getText ();
                    String price = jlbPrice.getText ();

                    //Passing
                    ticketReservation frame = new ticketReservation(name, date, time, price, total, String.valueOf(number));
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setTitle("Ticket Reservation"); //set title of the window
                    frame.setSize(800,600); //size of the window
                    frame.setVisible(true); //visible the window
                    frame.setLocationRelativeTo (null); //center the window

                }

                if((e.getSource() == jCancel))  {

                    listOfMovies frame = new listOfMovies ();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setTitle("List of Movies"); //set title of thewindow
                    frame.setSize(800,600); //size of the window
                    frame.setVisible(true); //visible the window
                    frame.setLocationRelativeTo (null); //center the window

                }
        }

        public static void main (String [] args) {

            bookBatman frame = new bookBatman ();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("Book Batman : The Dark Knight"); //set title of thewindow
            frame.setSize(800,600); //size of the window
            frame.setVisible(true); //visible the window
            frame.setLocationRelativeTo (null); //center the window

        }


}

最佳答案

不要将其视为将信息从一个 GUI 传递到另一个 GUI,而是将其视为最基本的 OOP 形式:将对象状态从一个对象传递到另一个对象。我们经常使用公共(public)访问器方法(即“getter”方法)来达到此目的,这也可以在这里工作。

您的 ButtonGroup 对象将保存所选 JRadioButton 的 ButtonModel(如果没有选择,则为 null),因此您可以从模型中获取信息并从 getter 方法返回它。

顺便说一句,您的代码有很多冗余,可以通过使用数组和适当的布局管理器来减少这些冗余。

编辑1:
例如
假设我们创建一个包含一堆 JRadioButton 的 JPanel:

import java.awt.GridLayout;
import javax.swing.*;

class RadioBtnDialogPanel extends JPanel {
   private static final String[] BUTTON_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
   private ButtonGroup buttonGroup = new ButtonGroup();

   public RadioBtnDialogPanel() {
      setLayout(new GridLayout(0, 1));  // give JPanel a decent layout

      // create radio buttons, add to button group and to JPanel
      for (String buttonText : BUTTON_TEXTS) {
         JRadioButton radioBtn = new JRadioButton(buttonText);
         radioBtn.setActionCommand(buttonText); // set the actionCommand here
         buttonGroup.add(radioBtn);
         add(radioBtn);
      }
   }

   // getter or accessor method to get selected JRadioButton's actionCommand text
   public String getSelectedButtonText() {
      ButtonModel model = buttonGroup.getSelection();
      if (model == null) { // no radiobutton selected
         return "";
      } else {
         return model.getActionCommand();
      }
   }
}

我们还为它提供了一个公共(public) getter 方法,用于查询 ButtonGroup 的状态以找出已选择的按钮模型,然后返回其 actionCommand,这是一个包含描述单选按钮的文本的字符串(此处与单选按钮的文本)。

然后,我们可以在主 GUI 的 JOptionPane 中显示此 JPanel,并在 JOptionPane 完成后,通过调用其 getSelectedButtonText() 方法来查询上面的对象:

import java.awt.event.*;
import javax.swing.*;

public class RadioButtonInfo extends JPanel {
   private RadioBtnDialogPanel radioBtnDlgPanel = new RadioBtnDialogPanel();
   private JTextField textfield = new JTextField(10);

   public RadioButtonInfo() {
      JButton getDayOfWeekBtn = new JButton("Get Day Of Week");
      getDayOfWeekBtn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            getDayOfWeekActionPerformed();
         }
      });
      textfield.setFocusable(false);

      add(getDayOfWeekBtn);
      add(textfield);
   }

   private void getDayOfWeekActionPerformed() {
      // display a JOptionPane that holds the radioBtnDlgPanel
      int result = JOptionPane.showConfirmDialog(this, radioBtnDlgPanel, "Select Day Of Week", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) { // if use presses "OK" get the selected radio button text
         // here we call the getter method  to get the selected button text
         String selectedButtonText = radioBtnDlgPanel.getSelectedButtonText();  
         textfield.setText(selectedButtonText); // and put it into a JTextField
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("RadioButtonInfo");
      frame.getContentPane().add(new RadioButtonInfo());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

关于Java-将选择的一个单选按钮的值传递到另一框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765010/

相关文章:

javascript - 如何验证输入 150 个字符后文本区域中是否出现滚动条

java - WSDL 中元素具有相同的名称和不同的类型

java - 使用 Eclipse 插件将焦点设置到 Project Explorer

java - setEnabled(true) 当 radioButton.isSelected()

java - 使用单选框/复选框实现 JTree 节点

Java:如何根据选择的单选按钮更改图像面板中的图像

java - 根据时间值返回不同的值

java - 编译代码后不出现JFrame

java - 优化 jtable

java - 为什么我不能将 ArrayList 直接添加到 Jlist 中?