0

Here is my code:

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

public class wind extends JFrame implements ComponentListener, MouseListener
{
    JButton button;
    JLabel label;
    public wind()
    {
        // initialise instance variables
        setTitle("My First Window!");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.addComponentListener(this);
        content.addMouseListener(this);

        label = new JLabel("My First Window");
        content.add(label);
        label.addComponentListener(this);
        button = new JButton("Click If You Wish To Live!");
        button.addMouseListener(this);
        content.add(button)
        setContentPane(content);

    }
    public void componentHidden(ComponentEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        button.setText("Hidden!");
    }
    public void componentShown(ComponentEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        button.setText("Shown!");
    }
    public void componentResized(ComponentEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        button.setText("Resized!");
    }
    public void componentMoved(ComponentEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        button.setText("Moved!");
    }
    public void mouseExited(MouseEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        label.setText("Exited!");
    }
    public void mouseEntered(MouseEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        label.setText("Entered!");
    }
    public void mousePressed(MouseEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        label.setText("pressed at: "+e.getX()+" "+e.getY());
    }
    public void mouseReleased(MouseEvent e){
        try{wait(100);}
        catch(InterruptedException error){}
        label.setText("Released!");
        label.setLocation(e.getX(), e.getY());
    }
    public void mouseClicked(MouseEvent e){}
}

It won't respond to the mouse or window re-sizing, hiding, or moving. Furthermore the button is not being displayed. fixed! I am just starting to learn about Java's JFrame and other graphics so I have no idea what's wrong with my code, although I suspect it has something to do with the way I made the button and added the listeners to the objects. Could someone please explain why it does this, and how to fix it. Thank you in advance!

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
tox123
  • 318
  • 9
  • 21
  • ok that was part of the issue, must have over looked that, :P – tox123 Aug 10 '14 at 23:15
  • I create it in the [environment](http://www.bluej.org/) that I use. – tox123 Aug 10 '14 at 23:20
  • yes, I think just `wait(some_num)` right? and besides it shouldn't effect the rest off my code right? – tox123 Aug 10 '14 at 23:28
  • That's an extremely loaded question -- yes it will effect your code completely. Why are you calling this anyway? – Hovercraft Full Of Eels Aug 10 '14 at 23:30
  • So that there is a delay between the changing of the labels. – tox123 Aug 10 '14 at 23:31
  • As an aside, you will want to learn and use [Java naming conventions](http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java). Variable names should all begin with a lower letter while class names with an upper case letter. Following these suggestions as well as following good code formatting practices will allow others (such as us!) to better understand your code, and more importantly, will allow your future self to better understand just what you were thinking 6 months ago when you wrote the code. – Hovercraft Full Of Eels Aug 10 '14 at 23:31
  • That's not how you do delays in Swing, but rather that's how you completely disable your GUI rendering it useless. Use a Swing Timer (Google the tutorial) for delays. – Hovercraft Full Of Eels Aug 10 '14 at 23:31
  • this code was mainly a self test to see if I could remember and implement what I just learned, not something I would use for a while. – tox123 Aug 10 '14 at 23:33
  • In fact your code is throwing a ton of exceptions due to the wait calls. – Hovercraft Full Of Eels Aug 10 '14 at 23:39
  • Also, don't add MouseListeners to JButtons but instead add ActionListeners. – Hovercraft Full Of Eels Aug 10 '14 at 23:41
  • @usar: The down-vote is not for your benefit, but for that of the original poster who can't tell a good recommendation from a bad one, and really needs to be shown that the recommendation that you gave was not a good idea. I am prompt to remove my down-vote once the problem has been corrected. And if you have tested the `Thread.sleep(...)` within mouseReleased and found it to "work" then your testing is bad. This will most assuredly not work as intended and will put the entire GUI asleep for the sleep period, not a good thing to do. – Hovercraft Full Of Eels Aug 10 '14 at 23:42
  • the `addActionListener(...)` doesn't work. – tox123 Aug 11 '14 at 00:04
  • I don't know how to convert the listener to an ActionListener. – tox123 Aug 11 '14 at 00:09
  • What are you trying to have it do? What behaviors is it not following? – Hovercraft Full Of Eels Aug 11 '14 at 00:10
  • It i a mouse/component listener not a actionlisttener and they cant be swaped – tox123 Aug 11 '14 at 00:24

2 Answers2

4

Your problem is that you are using the wait function not correctly. Try to use the class javax.swing.Timer also known as a Swing Timer for delays in Swing programs, for simple animations and for repetitive actions. For more information see this example on stackoverflow: Java Wait Function

One possible way to add a ActionListener to a JButton:

// You are adding an ActionListener to the button
//Using the method addActionListener and a anonymous inner class
button.addActionListener(new ActionListener() {//anonymous inner class

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        button.setText("Text modified by an event called ActionEvent!");
    }
});
Community
  • 1
  • 1
nbro
  • 15,395
  • 32
  • 113
  • 196
3

I decided to play with similar code and came up with this bit of code that tries to show the state of things in a status bar at the bottom:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

@SuppressWarnings({ "serial"})
// so the compiler won't complain
public class MyWindPanel extends JPanel {
   private static final int PREF_W = 1200;
   private static final int PREF_H = 600;
   private static final String MOUSE_LOCATION = "Mouse Location [%04d, %04d]";
   private static final String COMPONENT_STATE = "Component: %-15s";
   private static final String TIMER_LABEL = "Elapsed Time: %02d:%02d:%02d:%03d";
   private static final int TIMER_DELAY = 20;
   private static final String MOUSE_STATE = "Mouse State: %-15s";
   public static final String BUTTON_TEXT = "Set MyWindPanel %s";

   private JLabel mouseLocation = new JLabel(
         String.format(MOUSE_LOCATION, 0, 0));
   private JLabel mouseState = new JLabel(String.format(MOUSE_STATE, ""));
   private JLabel componentState = new JLabel(
         String.format(COMPONENT_STATE, ""));
   private JLabel timerLabel = new JLabel(
         String.format(TIMER_LABEL, 0, 0, 0, 0));
   private long startTime = System.currentTimeMillis();
   private Action buttonAction = new MyButtonAction(String.format(BUTTON_TEXT, "Invisible"));
   private JPanel statusPanel;

   public MyWindPanel() {
      setBackground(Color.pink);
      Font font = new Font(Font.MONOSPACED, Font.BOLD, 14);
      mouseLocation.setFont(font);
      mouseState.setFont(font);
      componentState.setFont(font);
      timerLabel.setFont(font);

      statusPanel = new JPanel();
      statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.LINE_AXIS));
      statusPanel.add(mouseLocation);
      statusPanel.add(Box.createHorizontalStrut(25));
      statusPanel.add(mouseState);
      statusPanel.add(Box.createHorizontalStrut(25));
      statusPanel.add(componentState);
      statusPanel.add(Box.createHorizontalStrut(25));
      statusPanel.add(timerLabel);

      new Timer(TIMER_DELAY, new TimerListener()).start();
      MouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseMotionListener(myMouseAdapter);
      addMouseListener(myMouseAdapter);
      addComponentListener(new MyComponentListener());

      setLayout(new BorderLayout());
      // add(statusPanel, BorderLayout.PAGE_END);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   public Action getButtonAction() {
      return buttonAction;
   }

   public JComponent getStatusPanel() {
      return statusPanel;
   }

   private class TimerListener implements ActionListener {
      private static final int SECONDS_PER_MIN = 60;
      private static final int MSEC_PER_SEC = 1000;
      private static final int MIN_PER_HOUR = 60;

      @Override
      public void actionPerformed(ActionEvent evt) {
         if (!MyWindPanel.this.isDisplayable()) {
            ((Timer) evt.getSource()).stop(); // so timer will stop when program
                                              // over
         }
         long currentTime = System.currentTimeMillis();
         long diff = currentTime - startTime;
         int hours = (int) (diff / (MIN_PER_HOUR * SECONDS_PER_MIN * MSEC_PER_SEC));
         int minutes = (int) (diff / (SECONDS_PER_MIN * MSEC_PER_SEC))
               % MIN_PER_HOUR;
         int seconds = (int) ((diff / MSEC_PER_SEC) % SECONDS_PER_MIN);
         int mSec = (int) diff % MSEC_PER_SEC;

         timerLabel.setText(String.format(TIMER_LABEL, hours, minutes, seconds,
               mSec));
      }
   }

   private class MyComponentListener extends ComponentAdapter {

      @Override
      public void componentHidden(ComponentEvent e) {
         componentState.setText(String.format(COMPONENT_STATE, "Hidden"));
      }

      @Override
      public void componentMoved(ComponentEvent e) {
         componentState.setText(String.format(COMPONENT_STATE, "Moved"));
      }

      @Override
      public void componentResized(ComponentEvent e) {
         componentState.setText(String.format(COMPONENT_STATE, "Resized"));
      }

      @Override
      public void componentShown(ComponentEvent e) {
         componentState.setText(String.format(COMPONENT_STATE, "Shown"));
      }

   }

   private class MyButtonAction extends AbstractAction {
      public MyButtonAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         boolean visible = MyWindPanel.this.isVisible();
         String text = visible ? "Visible" : "Invisible";
         ((AbstractButton) e.getSource()).setText(String.format(BUTTON_TEXT, text));
         MyWindPanel.this.setVisible(!MyWindPanel.this.isVisible());

         Window win = SwingUtilities.getWindowAncestor(MyWindPanel.this);
         win.revalidate();
         win.repaint();
      }
   }

   private class MyMouseAdapter extends MouseAdapter {
      @Override
      public void mouseMoved(MouseEvent e) {
         mouseLocation.setText(String.format(MOUSE_LOCATION, e.getX(), e.getY()));
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         mouseState.setText(String.format(MOUSE_STATE, "Dragged"));
         mouseLocation.setText(String.format(MOUSE_LOCATION, e.getX(), e.getY()));
      }

      public void mousePressed(MouseEvent e) {
         mouseState.setText(String.format(MOUSE_STATE, "Pressed"));
      };

      public void mouseReleased(MouseEvent e) {
         mouseState.setText(String.format(MOUSE_STATE, "Released"));
      };

      public void mouseEntered(MouseEvent e) {
         mouseState.setText(String.format(MOUSE_STATE, "Entered"));
      };

      public void mouseExited(MouseEvent e) {
         mouseState.setText(String.format(MOUSE_STATE, "Exited"));
      };
   }

   private static void createAndShowGui() {
      MyWindPanel mainPanel = new MyWindPanel();

      JPanel topPanel = new JPanel();
      topPanel.add(new JButton(mainPanel.getButtonAction()));

      JFrame frame = new JFrame("MyWind");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.getContentPane().add(topPanel, BorderLayout.PAGE_START);
      frame.getContentPane().add(mainPanel.getStatusPanel(), BorderLayout.PAGE_END);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373