【问题标题】:Why won't my JFrame respond to mouse and window changes?为什么我的 JFrame 不响应鼠标和窗口的变化?
【发布时间】:2014-10-03 17:26:41
【问题描述】:

这是我的代码:

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 和其他图形,所以我不知道我的代码有什么问题,尽管我怀疑这与我制作按钮并将侦听器添加到对象的方式有关。有人可以解释为什么会这样,以及如何解决它。提前谢谢!

【问题讨论】:

  • 好的,这是问题的一部分,一定忽略了这一点,:P
  • 我在我使用的environment 中创建它。
  • 是的,我想只是wait(some_num) 对吧?除了它不应该影响我的代码的其余部分吗?
  • 这是一个非常繁重的问题——是的,它会完全影响您的代码。你为什么要打电话给这个?
  • 这样在更换标签之间会有延迟。

标签: java swing jframe window mouselistener


【解决方案1】:

您的问题是您没有正确使用wait 函数。尝试在Swing 程序中使用javax.swing.Timer 类,也称为Swing Timer for delays,用于简单动画重复动作。有关更多信息,请参阅 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!");
    }
});

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2010-10-14
      相关资源
      最近更新 更多