简体   繁体   中英

How to change the values of spinner and radio button if I click on a row from jtable (must depend on the values form jtable)

If I click a row(JTABLE), it must display the specific values back to the textfields/combobox/radiobutton/spinner. But in my case, it's just hard to retrieve the values back to the RADIO BUTTON and SPINNER.

package coffeeshop;

import java.awt.HeadlessException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;


public class coffeeframe extends javax.swing.JFrame {

    public coffeeframe() {
        initComponents();
        ArrayList coffeeArray = new ArrayList();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        btnAdd = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        coffeeType = new javax.swing.JComboBox<>();
        jLabel3 = new javax.swing.JLabel();
        coffeeName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        coffeePrice = new javax.swing.JTextField();
        quanOrder = new javax.swing.JSpinner();
        jLabel5 = new javax.swing.JLabel();
        dinein = new javax.swing.JRadioButton();
        togo = new javax.swing.JRadioButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 51));

        table.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        table.setForeground(new java.awt.Color(204, 0, 51));
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Customer", "Coffee Type", "Coffee Name", "Price", "Order Mode", "Quantity", "Total"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.setGridColor(new java.awt.Color(0, 102, 102));
        table.getTableHeader().setReorderingAllowed(false);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        btnAdd.setBackground(new java.awt.Color(204, 255, 204));
        btnAdd.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        btnAdd.setForeground(new java.awt.Color(102, 102, 102));
        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/Add-icon (1).png"))); // NOI18N
        btnAdd.setText("ADD ORDER");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        jPanel1.setBackground(java.awt.Color.gray);
        jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        jLabel1.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Customer");

        name.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
        name.setForeground(new java.awt.Color(51, 51, 51));
        name.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameActionPerformed(evt);
            }
        });

        coffeeType.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        coffeeType.setForeground(new java.awt.Color(102, 102, 102));
        coffeeType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose", "Esprezo                        $20", "Green Tea Frappe      $75", "Barako        $22", "Black Coffee              $28" }));
        coffeeType.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                coffeeTypeItemStateChanged(evt);
            }
        });
        coffeeType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                coffeeTypeActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Coffee name");

        coffeeName.setEditable(false);
        coffeeName.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
        coffeeName.setForeground(new java.awt.Color(102, 102, 102));
        coffeeName.setText(" ");
        coffeeName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                coffeeNameActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Coffee Type");

        jLabel4.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Coffee price");

        coffeePrice.setEditable(false);
        coffeePrice.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
        coffeePrice.setForeground(new java.awt.Color(102, 102, 102));
        coffeePrice.setText(" ");

        quanOrder.setFont(new java.awt.Font("Arial", 3, 11)); // NOI18N
        quanOrder.setModel(new javax.swing.SpinnerNumberModel(1, 1, 100, 1));

        jLabel5.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("Quantity");

        buttonGroup1.add(dinein);
        dinein.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        dinein.setForeground(new java.awt.Color(255, 255, 255));
        dinein.setSelected(true);
        dinein.setText("Dine-In");
        dinein.setBorder(null);
        dinein.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dineinActionPerformed(evt);
            }
        });

        buttonGroup1.add(togo);
        togo.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        togo.setForeground(new java.awt.Color(255, 255, 255));
        togo.setText("To-Go");
        togo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                togoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(name)
                                    .addComponent(coffeeType, 0, 163, Short.MAX_VALUE))
                                .addGap(112, 112, 112))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(togo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel5)))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(coffeePrice, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(coffeeType, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(coffeePrice, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(coffeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(togo, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(dinein, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(quanOrder, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jButton2.setBackground(new java.awt.Color(255, 204, 204));
        jButton2.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jButton2.setForeground(new java.awt.Color(102, 102, 102));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/edit-icon.png"))); // NOI18N
        jButton2.setText("EDIT ORDER");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setBackground(new java.awt.Color(255, 51, 51));
        jButton3.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jButton3.setForeground(new java.awt.Color(239, 234, 234));
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/coffeeshop/trash-icon.png"))); // NOI18N
        jButton3.setText(" ");

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 201, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
        try{
            int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();
            DefaultTableModel model = (DefaultTableModel)table.getModel();
            Coffee coffee = new Coffee(name.getText(),coffeeType.getSelectedItem().toString(),coffeeName.getText(),Integer.parseInt(coffeePrice.getText()),buttonGroup1.getSelection().getActionCommand(),(Integer)quanOrder.getValue(),total);

            coffeeArray.add(coffee);
            if(name.getText().trim().isEmpty()){
                                JOptionPane.showMessageDialog(null,"Complete the order details!");
            }else if(buttonGroup1.getSelection().getActionCommand()== null){
                                JOptionPane.showMessageDialog(null,"Complete the order details!");
            }else{
                   String customerName = name.getText();
                   String cofType = coffeeType.getSelectedItem().toString();
                   String cofName = coffeeName.getText();
                   int price = Integer.parseInt(coffeePrice.getText());
                   String OrderMode= buttonGroup1.getSelection().getActionCommand();
                   int quantity = (Integer)quanOrder.getValue();

                   Object[] rowCoffee = {customerName,cofType,cofName,price,OrderMode,quantity,total};
                   model.addRow(rowCoffee);
            }
        }catch(NumberFormatException | HeadlessException e){
                   JOptionPane.showMessageDialog(null,"Complete the order details!");

        }

    }                                      

    private void coffeeTypeActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
          String str_coffee_name = (String)coffeeType.getSelectedItem();
          String input_coffee_name = str_coffee_name.replaceAll("[^a-zA-Z]","");
          coffeeName.setText(input_coffee_name);

          String str_coffee_price = (String)coffeeType.getSelectedItem();
          String input_coffee_price = str_coffee_price.replaceAll("[^0-9]","");
          coffeePrice.setText(input_coffee_price);
    }                                          

    private void coffeeNameActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void togoActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        togo.setActionCommand("TO-GO");

    }                                    

    private void dineinActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        dinein.setActionCommand("DINE-IN");


    }                                      

    private void nameActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
    }                                    

    private void coffeeTypeItemStateChanged(java.awt.event.ItemEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        DefaultTableModel model = (DefaultTableModel)table.getModel();
        int i = table.getSelectedRow();
        int total = Integer.parseInt(coffeePrice.getText()) * (Integer)quanOrder.getValue();

           if(i >= 0) 
                {
                   model.setValueAt(name.getText(), i, 0);
                   model.setValueAt(coffeeType.getSelectedItem(), i, 1);
                   model.setValueAt(coffeeName.getText(), i, 2);
                   model.setValueAt(Integer.parseInt(coffeePrice.getText()), i, 3);
                   model.setValueAt(buttonGroup1.getSelection().getActionCommand(), i, 4);
                   model.setValueAt((Integer)quanOrder.getValue(), i, 5);
                   model.setValueAt(total, i, 6);
                }
                else{
                    System.out.println("Update Error");
                }

    }                                        

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {                                   
      try{
        DefaultTableModel model = (DefaultTableModel)table.getModel();
        int row = table.getSelectedRow();
          name.setText(model.getValueAt(row, 0).toString());
          coffeeType.setSelectedItem(table.getValueAt(row, 1).toString());
          coffeeName.setText(model.getValueAt(row, 2).toString());
          coffeePrice.setText(model.getValueAt(row, 3).toString());
          quanOrder.setValue(model.getValueAt(row, 5).toString());
      }catch(Exception e){

      }

    }                                  

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(coffeeframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new coffeeframe().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnAdd;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField coffeeName;
    private javax.swing.JTextField coffeePrice;
    private javax.swing.JComboBox<String> coffeeType;
    private javax.swing.JRadioButton dinein;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField name;
    private javax.swing.JSpinner quanOrder;
    private javax.swing.JTable table;
    private javax.swing.JRadioButton togo;
    // End of variables declaration                   
ArrayList<Coffee> coffeeArray = new ArrayList<>();
int length = 0;
}

How to change the values of spinner and radio button

  • The spinner should be easily settable by calling its setValue(...) method, and passing in the number from the selected table row item.
  • For the JRadioButtons, probably the easiest solution is to use a Map that maps the selection to its radio button, and then using this map to get a reference to the proper JRadioButton, and calling setSelected(true) on it.

For an example, and for an example of a Minimal, Complete, and Verifiable example , please have a look at:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.EnumMap;
import java.util.Map;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class CoffeeMcve extends JPanel {
    private CoffeeTableModel tableModel = new CoffeeTableModel();
    private JTable table = new JTable(tableModel);
    private Map<OrderMode, ButtonModel> modeButtonMap = new EnumMap<>(OrderMode.class);
    private JSpinner quantSpinner = new JSpinner(new SpinnerNumberModel(1, 0, 20, 1));
    private JTextField nameTField = new JTextField(10);
    private ButtonGroup modeBtnGroup = new ButtonGroup();

    public CoffeeMcve() {
        JPanel modePanel = new JPanel();
        modePanel.setBorder(BorderFactory.createTitledBorder("Order Mode"));
        for (OrderMode mode : OrderMode.values()) {
            JRadioButton rBtn = new JRadioButton(mode.getText());
            rBtn.setActionCommand(mode.toString());
            modeBtnGroup.add(rBtn);
            modePanel.add(rBtn);
            modeButtonMap.put(mode, rBtn.getModel());
        }

        JPanel orderPanel = new JPanel();
        orderPanel.add(new JLabel("Name:"));
        orderPanel.add(nameTField);
        orderPanel.add(new JLabel("Quantity:"));
        orderPanel.add(quantSpinner);
        orderPanel.add(modePanel);
        orderPanel.add(new JButton(new AddAction("Add", KeyEvent.VK_A)));

        table.getColumnModel().getColumn(2).setCellRenderer(new OrderModeColumnRenderer());

        JScrollPane scrollPane = new JScrollPane(table);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(orderPanel, BorderLayout.PAGE_END);

        table.getSelectionModel().addListSelectionListener(new MyTableListener());
    }

    public void setOrderData(CoffeeOrder2 order) {
        nameTField.setText(order.getName());
        quantSpinner.setValue(order.getQuant());
        ButtonModel btnModel = modeButtonMap.get(order.getOrderMode());
        modeBtnGroup.setSelected(btnModel, true);
    }

    private class MyTableListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                int index = table.getSelectedRow();
                CoffeeOrder2 order = tableModel.getRow(index);
                setOrderData(order);
            }
        }

    }

    private class OrderModeColumnRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            if (value != null && value instanceof OrderMode) {
                value = ((OrderMode) value).getText();
            }
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }
    }

    private class AddAction extends AbstractAction {
        public AddAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameTField.getText();
            int quant = (int) quantSpinner.getValue();
            ButtonModel model = modeBtnGroup.getSelection();
            if (model != null) {
                String actionCommand = model.getActionCommand();
                OrderMode orderMode = OrderMode.valueOf(actionCommand);
                CoffeeOrder2 coffeeOrder2 = new CoffeeOrder2(name, quant, orderMode);
                tableModel.addRow(coffeeOrder2);
            }
        }
    }

    private static void createAndShowGui() {
        CoffeeMcve mainPanel = new CoffeeMcve();

        JFrame frame = new JFrame("CoffeeMcve");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class CoffeeTableModel extends DefaultTableModel {
    public static final String[] TITLES = {"Name", "Quantity", "Order Mode"};

    public CoffeeTableModel() {
        super(TITLES, 0);
    }

    public void addRow(CoffeeOrder2 coffee2) {
        Vector<Object> rowData = new Vector<>();
        rowData.add(coffee2.getName());
        rowData.add(coffee2.getQuant());
        rowData.add(coffee2.getOrderMode());
        super.addRow(rowData);
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        Object value = getValueAt(0, columnIndex);
        if (value == null) {
            return super.getColumnClass(columnIndex);
        } else {
            return value.getClass();
        }
    }

    public CoffeeOrder2 getRow(int rowIndex) {
        if (rowIndex < 0 || rowIndex >= getRowCount()) {
            String text = "For rowIndex: " + rowIndex;
            throw new IllegalArgumentException(text);
        }

        String name = getValueAt(rowIndex, 0).toString();
        int quant = (int) getValueAt(rowIndex, 1);
        OrderMode orderMode = (OrderMode) getValueAt(rowIndex, 2);

        return new CoffeeOrder2(name, quant, orderMode);
    }
}

class CoffeeOrder2 {
    private String name;
    private int quant;
    private OrderMode orderMode;

    public CoffeeOrder2(String name, int quant, OrderMode orderMode) {
        this.name = name;
        this.quant = quant;
        this.orderMode = orderMode;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getQuant() {
        return quant;
    }

    public void setQuant(int quant) {
        this.quant = quant;
    }

    public OrderMode getOrderMode() {
        return orderMode;
    }

    public void setOrderMode(OrderMode orderMode) {
        this.orderMode = orderMode;
    }

}

enum OrderMode {
    HERE("Here"), TO_GO("To Go");

    private String text;

    private OrderMode(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM