Search code examples
javaarraysjbuttonjtextfield

JButtons need to modify 8 JTextFields using an Array. Listen to Buttons or Text?


This is homework, and this questions Extends this one

So there is a button for First, Prev, Next, and Last

Each should modify

Item ID, Name, Rating, Price, Units, Value, Fee, ValueW/Fee, Total Inventory Value 

The last one is a static total of all units.

I am not sure if I should make each button do multiple calls like this.

productName.setText( product.getProductName() );
itemNumber.setText( String.valueOf( product.getItemNumber() ) );

Or make each JTextArea listen for the button then change its field. Does that even work?


Solution

  • Register an ActionListener for each button. In the body of that ActionListener's actionPerformed method, get the item to display and pass it to a method that will be responsible for setting the values to the text fields.

    Something like:

    JButton button = new JButton("Next");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DVDObject obj = getNextDVD();
            populateFields(obj);
        }
    });
    
    ...
    
    private DVDObject getNextDVD() {
        // gets the next object to display
        // you could call this method for each of the buttons, 
        // passing in an argument that determines which Object
        // to return (first, last, next, previous, whatever)
    }
    
    private void populateFields(DVDObject dvd) {
        // write out the values from the object passed in to the
        // fields
    }
    

    I'm guessing you've got some kind of collection of objects that contain all the information about DVDs, I've taken a stab in the dark and called it "DVDObject" here.