从其他方法传递值

时间:2012-03-26 06:13:37

标签: java swing

我有问题,我是堆栈。如果有人有空闲时间,那就太好了。我试图从其他类中的getter传递值,但是它没有传递变量的值。例如在我的类toString方法中的主席我希望打印我在Class FurnitureItem中指定的值。 Chair是FurnitureItem的子类。我用setter方法设置值,当我尝试检索它时,它打印旧值。 按下addChair按钮时会发生这一切。具有main方法的类是RunFurniture,Panel和程序的GUI在PanelFurniture中。当程序运行并按下按钮addChair时,我们输入idNum,这是木材的int类型,是char或o数量是int,我们选择扶手或不选择布尔值。该程序正在编译和运行只是没有做我期望它做的事情。我正在使用eclipse。这是代码。

/** 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);

    }

}

这是该程序的GUI。

/** 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;
        }
    }

这是类Chair,它是FurnitureItem的子类。

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 个答案:

答案 0 :(得分:3)

看起来代码就是问题

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 :(得分:1)

首先,可能会导致问题的代码点,无法正常工作,您想要打印其他代码。其次,为什么要在Chair中创建新的Chair.toString()对象?