2013-11-09 3 views
0

Так что у меня проблема с моей программой Java. В настоящее время я хочу, чтобы у него было 3 основных варианта курса: гамбургер, пицца и салат с добавлением опций. Теперь в настоящее время программа начинается с выбранного гамбургера и доступных надстроек, которые они также вычисляют. Когда выбран основной элемент, дополнительные параметры должны меняться вместе с новым элементом, но они этого не делают. Я смотрел на это некоторое время, так что может быть, мне не хватает чего-то очень простого, как очистка области, а затем появление новых опций дополнения. В любом случае любая помощь будет оценена, вот текущий код.Группы радиостанций и дополнительные опции

import java.awt.*; 
import javax.swing.*; 
import java.text.DecimalFormat; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.ButtonGroup; 
import javax.swing.JRadioButton; 


public class LunchOrder extends JFrame { 

    private JRadioButton hamburgerJButton, pizzaJButton, saladJButton; 
    private JCheckBox lettuceButton, mayonnaiseButton, mustardButton, pepperoniButton, 
      sausageButton, mushroomsButton, croutonsButton, baconBitsButton, breadSticksButton; 
    private JLabel subTotal, tax, totalDue; 
    private JTextField subTotalText, taxText, totalDueText; 
    private JButton placeOrder, clearOrder, exitButton; 

    // no-argument constructor 
    public LunchOrder() 
    { 
     createUserInterface(); 
    } 

    // create and position GUI components; register event handlers 
    private void createUserInterface() 
    { 
     // get content pane for attaching GUI components 
     Container contentPane = getContentPane(); 

     // enable explicit positioning of GUI components 
     contentPane.setLayout(null); 

     hamburgerJButton = new JRadioButton("Hamburger - $6.95"); 
     hamburgerJButton.setSelected(true); 

     pizzaJButton = new JRadioButton("Pizza - $5.95"); 
     pizzaJButton.setSelected(false); 
     saladJButton = new JRadioButton("Salad - $4.95"); 
     saladJButton.setSelected(false); 
     ButtonGroup bgroup = new ButtonGroup(); 
     bgroup.add(hamburgerJButton); 
     bgroup.add(pizzaJButton); 
     bgroup.add(saladJButton); 

     JPanel mainCourse = new JPanel(); 
     mainCourse.setLayout(new GridLayout(3, 1)); 
     mainCourse.setBounds(10, 10, 150,135); 
     mainCourse.add(hamburgerJButton); 
     mainCourse.add(pizzaJButton); 
     mainCourse.add(saladJButton); 
     mainCourse.setBorder(BorderFactory.createTitledBorder(
       BorderFactory.createEtchedBorder(), "Main course")); 
     //contentPane.add(mainCourseJPanel, BorderLayout.NORTH); 
     contentPane.add(mainCourse); 
     //Add action listener to created button 

     //JCheckBox 

     lettuceButton = new JCheckBox("Lettuce, tomato, and onions"); 
     lettuceButton.setSelected(true); 

     mayonnaiseButton= new JCheckBox("Mayonnaise"); 
     mayonnaiseButton.setSelected(false); 

     mustardButton = new JCheckBox("Mustard"); 
     mustardButton.setSelected(true); 

     pepperoniButton = new JCheckBox("Pepperoni"); 
     sausageButton= new JCheckBox("Sausage"); 
     mushroomsButton = new JCheckBox("Mushrooms"); 
     croutonsButton = new JCheckBox("Croutons"); 
     baconBitsButton= new JCheckBox("Bacon bits"); 
     breadSticksButton = new JCheckBox("Bread sticks"); 

     //JPanel addons 
     JPanel addOns = new JPanel(); 
     GridLayout addOnGlay = new GridLayout(3,3); 
     addOns.setLayout(addOnGlay); 
     addOns.setBounds(250, 10, 250, 135); 
     addOns.add(lettuceButton); 
     addOns.add(pepperoniButton); 
     addOns.add(croutonsButton); 
     addOns.add(mayonnaiseButton); 
     addOns.add(sausageButton); 
     addOns.add(baconBitsButton); 
     addOns.add(mustardButton); 
     addOns.add(mushroomsButton); 
     addOns.add(breadSticksButton); 

     pepperoniButton.setVisible(false); 
     sausageButton.setVisible(false); 
     mushroomsButton.setVisible(false); 
     croutonsButton.setVisible(false); 
     baconBitsButton.setVisible(false); 
     breadSticksButton.setVisible(false); 

     addOns.setBorder(BorderFactory.createTitledBorder(
       BorderFactory.createEtchedBorder(), "Add ons($.25/each)")); 
     contentPane.add(addOns); 

     // subtotal JLabel 
     subTotal = new JLabel(); 
     subTotal.setBounds(10, 110, 100, 200); 
     contentPane.add(subTotal); 
     subTotal.setText("Subtotal: "); 
     subTotal.setHorizontalAlignment(JLabel.RIGHT); 

     // subtotal JTextField 
     subTotalText = new JTextField(); 
     subTotalText.setBounds(115, 200, 80, 22); 
     subTotalText.setHorizontalAlignment(JTextField.LEFT); 
     contentPane.add(subTotalText); 

     // Tax JLabel 
     tax = new JLabel(); 
     tax.setBounds(10, 135, 100, 200); 
     contentPane.add(tax); 
     tax.setText("Tax(7.85%) "); 
     tax.setHorizontalAlignment(JLabel.RIGHT); 

     // Tax JTextField 
     taxText = new JTextField(); 
     taxText.setBounds(115, 225, 80, 22); 
     contentPane.add(taxText); 

     // total due JLabel 
     totalDue = new JLabel(); 
     totalDue.setBounds(10, 160, 100, 200); 
     contentPane.add(totalDue); 
     totalDue.setText("Total due: "); 
     totalDue.setHorizontalAlignment(JLabel.RIGHT); 

     // total due JTextField 
     totalDueText = new JTextField(); 
     totalDueText.setBounds(115, 250, 80, 22); 
     contentPane.add(totalDueText); 

     // order total JPanel 
     JPanel orderTotal = new JPanel(); 
     GridLayout orderGLay = new GridLayout(3,1); 
     orderTotal.setLayout(orderGLay); 
     orderTotal.setBounds(10, 170, 200, 125); 

     orderTotal.setBorder(BorderFactory.createTitledBorder(
       BorderFactory.createEtchedBorder(), "Order total")); 
     contentPane.add(orderTotal); 

     // place order JButton 
     placeOrder = new JButton(); 
     placeOrder.setBounds(252, 175, 100, 24); 
     placeOrder.setText("Place order"); 
     contentPane.add(placeOrder); 
     placeOrder.addActionListener(
       new ActionListener() // anonymous inner class 
       { 
        // event handler called when calculateJButton is pressed 
        public void actionPerformed(ActionEvent event) { 
         placeOrderActionPerformed(event); 
        } 

       } // end anonymous inner class 

    ); // end call to addActionListener 

     // set up clearOrderJButton 
     clearOrder = new JButton(); 
     clearOrder.setBounds(252,210, 100, 24); 
     clearOrder.setText("Clear order"); 
     contentPane.add(clearOrder); 
     clearOrder.addActionListener(
       new ActionListener() // anonymous inner class 
       { 
        // event handler called when calculateJButton is pressed 
        public void actionPerformed(ActionEvent event) { 
         clearOrderActionPerformed(event); 
        } 

       } // end anonymous inner class 

    ); // end call to addActionListener 

     // set up exitJButton 
     exitButton = new JButton(); 
     exitButton.setBounds(425, 260, 70, 24); 
     exitButton.setText("Exit"); 
     contentPane.add(exitButton); 

     // set properties of application's window 
     setTitle("Lunch order"); // set window title 
     setResizable(true);  // prevent user from resizing window 
     setSize(525, 350);  // set window size 
     setVisible(true);  // display window 
     setLocationRelativeTo(null); 
    } 
    // calculate subtotal plus tax 
    private void placeOrderActionPerformed(ActionEvent event) { 

     DecimalFormat dollars = new DecimalFormat("$0.00"); 

     // declare double variables 
     double hamburgerPrice = 6.95; 
     double pizzaPrice = 5.95; 
     double saladPrice = 4.95; 

     double addons = 0; 
     double subTotPrice; 
     double taxPercent; 
     double totalDuePrice; 

     if (hamburgerJButton.isSelected()) 
     { 
      if(lettuceButton.isSelected()){ 
       addons += 0.25; 
      } 
      if(mayonnaiseButton.isSelected()){ 
       addons += 0.25; 
      } 
      if(mustardButton.isSelected()){ 
       addons += 0.25; 
      } 
      else{ 
       addons -= 0.25; 
      } 

      subTotPrice = hamburgerPrice + addons; 

       taxPercent = subTotPrice * 0.0785; 
       totalDuePrice = subTotPrice + taxPercent; 

       //display subtotal, tax and total due 
       subTotalText.setText(dollars.format(subTotPrice)); 
       taxText.setText(dollars.format(taxPercent)); 
       totalDueText.setText(dollars.format(totalDuePrice)); 

     } 
     if (pizzaJButton.isSelected()) 
     { 
      //lettuceButton.setVisible(false); 
      //mayonnaiseButton.setVisible(false); 
      //mustardButton.setVisible(false); 
      croutonsButton.setVisible(false); 
      baconBitsButton.setVisible(false); 
      breadSticksButton.setVisible(false); 
      pepperoniButton.setVisible(true); 
      sausageButton.setVisible(true); 
      mushroomsButton.setVisible(true); 
      //calculation for pizza selection 

      if(pepperoniButton.isSelected()) 
       addons += 0.25; 
      if(sausageButton.isSelected()) 
       addons += 0.25; 
      if(mushroomsButton.isSelected()) 
       addons += 0.25; 
      else 
       addons -= 0.25; 

      subTotPrice = (pizzaPrice + addons); 
      taxPercent = subTotPrice * 0.0785; 
      totalDuePrice = subTotPrice + taxPercent; 

      //display subtotal, tax and total due 
      subTotalText.setText(dollars.format(subTotPrice)); 
      taxText.setText(dollars.format(taxPercent)); 
      totalDueText.setText(dollars.format(totalDuePrice)); 
     } 
     if (saladJButton.isSelected()) 
     { 
      croutonsButton.setVisible(true); 
      baconBitsButton.setVisible(true); 
      breadSticksButton.setVisible(true); 

      if(croutonsButton.isSelected()) 
       addons += 0.25; 
      if(baconBitsButton.isSelected()) 
       addons += 0.25; 
      if(breadSticksButton.isSelected()) 
       addons += 0.25; 
      else 
       addons -= 0.25; 

      //calculation for salad selection 
      subTotPrice = (saladPrice + addons); 
      taxPercent = subTotPrice * 0.0785; 
      totalDuePrice = subTotPrice + taxPercent; 

      //display subtotal, tax and total due 
      subTotalText.setText(dollars.format(subTotPrice)); 
      taxText.setText(dollars.format(taxPercent)); 
      totalDueText.setText(dollars.format(totalDuePrice)); 
     } 

    } // end method calculateJButtonActionPerformed 

    private void clearOrderActionPerformed(ActionEvent event) { 

      //reset hamburger and addons to default state 
      hamburgerJButton.setSelected(true); 
      lettuceButton.setSelected(true); 
      mayonnaiseButton.setSelected(false); 
      mustardButton.setSelected(true); 

      subTotalText.setText(""); 
      taxText.setText(""); 
      totalDueText.setText(""); 


    } // end method calculateJButtonActionPerformed 


    public static void main(String args[]) 
    { 
     LunchOrder application = new LunchOrder(); 
     application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

} 
+0

Теперь, почему я не могу видеть ничего, кроме пустого JFrame? –

+0

Я не уверен, вы имеете в виду на сайте, или вы его скопировали и скомпилировали? –

+0

Скопировано и скомпилировано. Ничего. –

ответ

3

Вы не добавил слушателей, которые могли бы известить любого рода изменения состояния, Java не может волшебно знать, что вы хотите, чтобы это ... Я желаю ...

Вы можете использовать ItemListener на каждой из кнопок, и на основании того, что выбрано, внести изменения в ваш пользовательский интерфейс, например ...

НАПИСАТЬ вы самостоятельно в ItemListener ...

ItemListener il = new ItemListener() { 
    @Override 
    public void itemStateChanged(ItemEvent e) { 
     if (e.getStateChange() == ItemEvent.SELECTED) { 
      System.out.println("Hamburger = " + hamburgerJButton.isSelected()); 
      System.out.println("Pizza = " + pizzaJButton.isSelected()); 
      System.out.println("Salad = " + saladJButton.isSelected()); 
     } 
    } 
}; 

й после того как вы initalised ваших кнопок, зарегистрировать его с каждым из них ...

hamburgerJButton.addItemListener(il); 
pizzaJButton.addItemListener(il); 
saladJButton.addItemListener(il); 

Посмотрите на How to use buttons для получения более подробной информации

+0

Я прочитал статью и стараюсь понять, что вы говорите. Нужно ли мне импортировать что-нибудь еще для этого? Нужно ли сделать первый раздел ItemListener в его собственном разделе похожим на что-то вроде этого: private void clearOrderActionPerformed (событие ActionEvent) Еще раз спасибо за помощь, а не собираюсь лежать. Я почувствовал себя глупым после того, как прочитал, что было неправильно. Не могу поверить, что я пропустил что-то подобное! –

+1

Другое, тогда 'import' для' ItemListener' и 'ItemEvent' не очень. Вы можете сделать «ItemListener» анонимным классом, как у меня, или создать его как внутренний класс, исходя из ваших потребностей. – MadProgrammer

+0

. Получил его, как только я добавил импорт, спасибо за помощь! Также я пошел с тем, чтобы сделать его внутренним классом для каждой кнопки, работал как шарм! –

Смежные вопросы