为什么我的JFrame不会响应鼠标和窗口的变化?

时间:2014-08-10 23:09:51

标签: java swing jframe window mouselistener

这是我的代码:

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){}
}

它不会响应鼠标或窗口重新调整大小,隐藏或移动。 此外,按钮未显示。已修复!我刚刚开始学习Java的JFrame和其他图形,所以我不知道我的代码有什么问题,虽然我怀疑它与我制作按钮的方式有关并将侦听器添加到对象中。有人可以解释为什么会这样做,以及如何解决它。提前谢谢!

2 个答案:

答案 0 :(得分:4)

您的问题是您未正确使用wait功能。尝试在javax.swing.Timer程序中使用Swing Timer for delaysSwing简单动画重复操作。有关更多信息,请参阅stackoverflow上的此示例:Java Wait Function

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

答案 1 :(得分:3)

我决定使用类似的代码,并想出了一些代码,试图在底部的状态栏中显示事物的状态:

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