Why won't my JFrame respond to mouse and window changes?

我与影子孤独终老i 提交于 2020-01-14 06:36:47

问题


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!


回答1:


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!");
    }
});



回答2:


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();
         }
      });
   }
}


来源:https://stackoverflow.com/questions/25233881/why-wont-my-jframe-respond-to-mouse-and-window-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!