передача значения из других методов - PullRequest
0 голосов
/ 26 марта 2012

У меня проблема, и я стек.Если бы у кого-нибудь был свободный момент, было бы здорово.Я пытаюсь передать значения из других методов получения, которые находятся в другом классе, но он не передает значения переменных.Например, в моем классе Chair в методе toString я ожидаю напечатать значения, которые я назначил в классе FurnitureItem.Стул является подклассом FurnitureItem.Я устанавливаю значения с помощью методов установки, и когда я пытаюсь получить их, он печатает старые значения.Все это происходит при нажатии кнопки addChair.Класс с методом main называется RunFurniture, а Panel и GUI программы находятся в PanelFurniture.Когда программа запущена и нажата кнопка addChair, мы вводим idNum, который является типом дерева int, который представляет собой символ char или количество int, и мы выбираем подлокотник или не логическое значение.Программа компилируется и запускается, но не делает то, что я ожидаю.Я использую затмение.Вот код.

/** This is the driver class of the program.
 * Here is the main method with the JFrame.
 * class name RunFurniture.class
 * @author Kiril Anastasov
 * @date 18/03/2012
 */

import java.awt.*;
import javax.swing.*;
public class RunFurniture 
{

    /**
     * @param args
     */
    public static void main(String[] args) 
    {

        JFrame application = new JFrame();
        PanelFurniture panel = new PanelFurniture();
        application.add(panel);
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.setSize(650,650);
        application.setLocationByPlatform(true);
        application.setVisible(true);

    }

}

Вот графический интерфейс программы.

/** Here is the GUI of the program.
 * class name PanelFurniture.class
 * @author Kiril Anastasov
 * @date 18/03/2012
 */

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

public class PanelFurniture extends JPanel implements ActionListener
{
    //FurnitureItem my = new FurnitureItem("");  the class is abstract so you cannot make an object from it.

    JButton center, east;
    JButton[] commandButtons = {
                                 new JButton(" Add Chair"),
                                 new JButton(" Add Table"),
                                 new JButton(" Add Desk "),
                                 new JButton(" Clear All   "),
                                 new JButton("Total Price   "),
                                 new JButton("   Save       "),
                                 new JButton("   Load       "),
                                 new JButton("Summary ")
                                                        };
    JLabel  desks;
    JLabel[] chairsAndTables  = {
                                    new JLabel("Possition 1"),
                                    new JLabel("Possition 2"),
                                    new JLabel("Possition 3"),
                                    new JLabel("Possition 4"),
                                    new JLabel("Possition 5"),
                                    new JLabel("Possition 6")};

    protected ImageIcon[] image = { new ImageIcon("Pictures/Chair1.png"),
                                    new ImageIcon("Pictures/Chair2.png"),
                                    new ImageIcon("Pictures/Desk1.png"),
                                    new ImageIcon("Pictures/Desk2.png"),
                                    new ImageIcon("Pictures/Desk3.png"),
                                    new ImageIcon("Pictures/Desk4.png"),
                                    new ImageIcon("Pictures/Table1.png"),
                                    new ImageIcon("Pictures/Table2.png")};

    JPanel centerPanel, westPanel, eastPanel, leftPanel, rightPanel;

    PanelFurniture()
    {

        this.setLayout(new BorderLayout());


         westPanel = new JPanel();
         westPanel.setLayout(new BoxLayout(westPanel, BoxLayout.PAGE_AXIS));

        for(int i=0; i<commandButtons.length; i++)      
        {
            westPanel.add(commandButtons[i]);
            commandButtons[i].addActionListener(this);

        }

        this.add(westPanel, BorderLayout.WEST);

        // split the panel by 2     
        centerPanel = new JPanel(new GridLayout(1,2));

        // split the left half for the chairs and the tables
        leftPanel = new JPanel(new GridLayout(3,2));

        for(int j=0; j<chairsAndTables.length; j++)
        {       
            leftPanel.add(chairsAndTables[j]);
        }
        centerPanel.add(leftPanel);

        //split the right part of the middle for the desks
        rightPanel = new JPanel(new GridLayout(3,1));

        desks = new JLabel(image[2]);
        rightPanel.add(desks);
        desks = new JLabel("2");
        rightPanel.add(desks);
        desks = new JLabel("3");
        rightPanel.add(desks);
        centerPanel.add(rightPanel);



        this.add(centerPanel, BorderLayout.CENTER);


    }

    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource() == commandButtons[0])
        {
            Chair myChair  = new Chair(); // create an object of type Chair
            myChair.setIdNum(0); // ask the user for the Id of the chair
            System.out.println(myChair.getIdNum()); // print the id of the chair

            myChair.setTypeOfWood('w');
            System.out.println(myChair.getTypeOfWood());

            myChair.setQuantity(0);
            System.out.println(myChair.getQuantity());

            myChair.setArmRest(false);
            System.out.println(myChair.getArmRest());

            System.out.println(myChair.toString());

            if(myChair.getArmRest() == true)
            {
                chairsAndTables[0].setIcon(image[1]);

            }
            else
            {
                chairsAndTables[0].setIcon(image[0]);   
            }
        }

        if(ae.getSource() == commandButtons[1])
        {
            Table myTable = new Table();

            myTable.setIdNum(0);
            System.out.println(myTable.getIdNum());
            myTable.setTypeOfWood('o');
            System.out.println(myTable.getTypeOfWood());
            myTable.setQuantity(2);
            System.out.println(myTable.getQuantity());
            System.out.println(myTable.toString());
            System.out.println(myTable.getIdNum());

        }       
    }
}

Это класс FurnitureItem, который является абстрактным и суперклассом для Chair

import java.io.Serializable;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;

    import java.util.Scanner;
    /** Here is the super class for Chair, Desk, Table
     * class name FurnitureItem.class
     * I have inlcuded the methods setTypeOfWood setIdNum and getIdNum.
     * @author Kiril Anastasov
     * @date 18/03/2012
     */

    abstract class FurnitureItem  implements Serializable
    {
        private int idNum;
        private char typeOfWood;
        protected double itemPrice;
        private int quantity;

        protected ImageIcon[] image; /*= { new ImageIcon("Pictures/Chair1.png"),
                                        new ImageIcon("Pictures/Chair2.png"),
                                        new ImageIcon("Pictures/Desk1.png"),
                                        new ImageIcon("Pictures/Desk2.png"),
                                        new ImageIcon("Pictures/Desk3.png"),
                                        new ImageIcon("Pictures/Desk4.png"),
                                        new ImageIcon("Pictures/Table1.png"),
                                        new ImageIcon("Pictures/Table2.png")};
                                        */

        //default constructor
        public FurnitureItem()
        {

            idNum = 0;
            typeOfWood = 'o' ; //oak or walnut
            itemPrice = 0;
            quantity = 0;
            image = null;

        }

        //parameterized constructor
        public FurnitureItem(int id, char tw, int qty, ImageIcon[] img)
        {
            idNum = id;
            typeOfWood = tw;
            itemPrice = 0;
            quantity = qty;
            image = img;
        }

        //mutator method for the id num
        public void setIdNum(int id)
        {
            String prompt = "Please enter furniture's id number: \n" +
                            "furniture's id must be numbers only";  

            String tablesIdNumber = JOptionPane.showInputDialog(null, prompt);
            Scanner input = new Scanner(tablesIdNumber);
            id = input.nextInt();
            idNum = id;     

        }

        //accesor method for the id
        public int getIdNum()
        {
            return idNum;

        }

        public double getItemPrice()
        {   
            return itemPrice;
        }

        public double getTotalPrice()
        {
            return itemPrice * 0.03; // incomplete
        }

        //mutator method for type of wood
        public void setTypeOfWood(char tw)
        {
            String prompt = "Please enter type of wood: \n" +
                    "type of wood can be oak or walnut";
            boolean validFlag;
            do
            {                   
                    String chairsTypeOfWood = JOptionPane.showInputDialog(null, prompt);
                    prompt = "Invalid data, please re-enter type of wood o for oak and w for walnut";
                    Scanner input = new Scanner(chairsTypeOfWood);
                    validFlag = true;
                    tw = input.nextLine().charAt(0);
                    if(tw != 'o' && tw != 'w')
                    {
                        validFlag = false;
                    }

            }while(!validFlag);
            typeOfWood = tw;

        }

        //accesor method for type of wood
        public char getTypeOfWood()
        {
            return typeOfWood;
        }

        //mutator method for quantity
        public void setQuantity(int qty)
        {

            String prompt = "Please enter quantity. \n" +
                    "How many furnitures would you like";
            boolean validFlag;
            do
            {


                String chairsQuantity = JOptionPane.showInputDialog(null, prompt);
                prompt = "Invalid data, the quantity of the chairs must be a possitive number, please re-enter";
                Scanner input = new Scanner(chairsQuantity);
                validFlag = true;
                qty = input.nextInt();
                if(qty < 0)
                {
                    validFlag = false;
                }


            }while(!validFlag);
            quantity = qty;
        }

        // accesor method for quantity
        public int getQuantity()
        {
            return quantity;
        }



        public ImageIcon[] getImage()
        {
            return image;
        }

        public String toString()
        {
            return "The id is: " + idNum + " and the qunatity is: " + quantity +
                    "the type of wood is:" + typeOfWood +" and the price of the item is: " + itemPrice;
        }

        public  int calcUnits() // make it abstract
        {
            return 5;
        }
    }

И это класс Стул, который является подклассом Элемента Мебели.

import javax.swing.ImageIcon;
import java.util.Scanner;
import javax.swing.JOptionPane;

/** Here is the sub class for FurnitureItem
 * class name Chair.class
 * @author Kiril Anastasov
 * @date 18/03/2012
 */
public class Chair extends FurnitureItem
{
//  private int idNum;
//  private char typeOfWood;
//  private int quantity;
    private boolean armRest;
//  Chair useChair = new Chair();


    //default constructor
    public Chair()
    {
        armRest = false;
        image = null;
        itemPrice = 0.0;
//      idNum = 0;
//      typeOfWood = 0;
//      quantity = 0;
    }

    //parameterized constructor
    public Chair(int id, char tw, int qty, ImageIcon[] img, boolean a)
    {

//      idNum = id;
//      typeOfWood = tw;    
//      quantity = qty;
        image = null;
        itemPrice = 0.0;        
        armRest = a;     

    }


    public void setArmRest(boolean a)
    {
        String[] withArmRest = {"Yes please", "No thank you"};
        String prompt = "Would you like an armrest for the chair";
        int option = JOptionPane.showOptionDialog(null, 
                                                  prompt,
                                                  "ArmRest",
                                                  JOptionPane.YES_NO_OPTION,
                                                  JOptionPane.QUESTION_MESSAGE,
                                                  null,
                                                  withArmRest,
                                                  withArmRest[0]);

        if(option == 0)
        {
            a = true;
        }
        else
        {
            a = false;
        }

        armRest = a;
        //System.out.println(useChair.toString());
    }
    public boolean getArmRest()
    {
        return armRest;
    }

    public String toString()
    {
        Chair myChair = new Chair();
        return "The id is: " + myChair.getIdNum() + " and the price of the item is: " + myChair.getTotalPrice() +
                " Is there an armrest ? ==> " + getArmRest() ;
    }
    public int calsUnits()
    {
        return getQuantity();
    }
}

Ответы [ 2 ]

3 голосов
/ 26 марта 2012

Выглядит так, как будто проблема в коде

public String toString() 
    { 
        Chair myChair = new Chair(); 
        return "The id is: " + myChair.getIdNum() + " and the price of the item is: " + myChair.getTotalPrice() + 
                " Is there an armrest ? ==> " + getArmRest() ; 
    } 

Вы создаете новый экземпляр и печатаете значения нового экземпляра. Вместо myChair.getIdNum() используйте this.getIdNum()

1 голос
/ 26 марта 2012

Прежде всего, укажите строки кодов, которые могут вызвать проблему, которые не работают должным образом, которые вы хотели бы напечатать в другом месте. Во-вторых, почему вы создаете новый Chair объект в Chair.toString()?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...