Page 1 of 1

Java assignment dealing with events

Posted: Mon Jul 08, 2013 3:23 am
by Jessica
Trying to code up something that uses events...I have it written up, and there are no errors, but it's not working as it should.
Code: Select all
/* Jessica Chen
 * Sunday 7/7/13
 * Java 1.7.0_21 and NetBeans 7.3
 * This program displays a glass of milk
 */

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


public class Milk extends JComponent implements ActionListener {
   JFrame frame = new JFrame("Glass of Milk");
   Container content = frame.getContentPane();
   JPanel panel = new JPanel();
   JButton drinkAll = new JButton("Drink");
   boolean drink = true;

    public static void main(String[] args) {
        Milk drawing = new Milk();
    }
    
    public void paint(Graphics g){
        g.drawLine(90, 100, 90, 130);
        g.drawLine(115, 100, 115, 130);
        g.drawLine(90, 130, 115, 130);
        if (drink = false){
             g.setColor(Color.WHITE);
             g.fillRect(91, 105, 24, 25);
        } else {
             g.fillRect(0, 0, 0, 0);
        }
    }
    
    public Milk(){
        content.setLayout(new BorderLayout());
        content.setBackground(Color.lightGray);
        content.add(this, BorderLayout.CENTER);
        
        panel.add(drinkAll);
        content.add(panel, BorderLayout.SOUTH);
        
        frame.setSize(200, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        
        drinkAll.addActionListener(this);
        
    }
    
    public void actionPerformed(ActionEvent e){
        content.repaint();
        
        String cmd = e.getActionCommand();
        
        if (cmd.equals("Drink")) {
            drink = true;
        } else {
            drink = false;
        }
    }
}

What I have drawn is a glass of milk. When I click the button "Drink", the milk (white rectangle) disappears. Something in my code is not making it disappear when I click it. I know I have something wrong, or am missing something, but I don't know what. Someone help please?



Get in asap please, due tomorrow before midnight EST

Re: Java assignment dealing with events

Posted: Mon Jul 08, 2013 7:14 am
by XTechVB
have you tried Refreshing or Invalidating the container after you click the button?

In the actionPerformed event try calling the content.repaint(); method after the IF statement. like this:
Code: Select all
    public void actionPerformed(ActionEvent e){
        String cmd = e.getActionCommand();
       
        if (cmd.equals("Drink")) {
            drink = true;
        } else {
            drink = false;
        }
        content.repaint();
    }

Re: Java assignment dealing with events

Posted: Tue Jul 09, 2013 3:48 pm
by Jessica
Managed to solve it myself...thanks for the help anyways