在Netbeans中获取JFrame边界的问题

Thu*_*tha 5 java swing timer jframe bounds

我想在我的程序中按下按钮时,将JFrame动画化为半角.我认为最简单的方法是将JFrame的当前边界放入计时器,并在计时器运行时将边界减1,但是当我在netbeans IDE中声明一个新的计时器时,它看起来像这样.

      Timer t = new Timer(5,new ActionListener() {

        public void actionPerformed(ActionEvent e) {

          //inside this I want to get my Jframe's bounds like this
           //    int width = this.getWidth();---------here,"this" means the Jframe

           }

        }
    });
Run Code Online (Sandbox Code Playgroud)

但问题是在这里"这个"并没有引用JFrame.And我甚至无法创建我的JFrame的新对象.因为它会给我另一个窗口.任何人都可以帮我解决这个问题吗?

mre*_*mre 5

尝试

int width = Foo.this.getWidth();
Run Code Online (Sandbox Code Playgroud)

其中Foo的子类JFrame.

  • 如果定时器代码是主类的内部代码,并且主类继承JFrame(因此1+ upvote用于此答案),这应该有效,但是不管这些限制如何,camickr的推荐都会起作用(因此对于camickr的回答是1+). (2认同)

cam*_*ckr 5

我想在我的程序中按下按钮时,将JFrame动画化为半角

因此,当您单击按钮时,您可以访问该按钮.然后你可以使用:

SwingUtilities.windowForComponent( theButton );
Run Code Online (Sandbox Code Playgroud)

获取对框架的引用.

因此,现在当您为Timer创建ActionListener时,您可以将Window作为ActionListener的参数传递.

编辑:

在许多情况下,mre的建议简单直接且易于使用(在这种情况下可能是更好的解决方案).

我的建议稍微复杂一些,但它向您介绍了SwingUtilities方法,该方法最终允许您编写更多可重用的代码,这些代码可能被您可能创建的任何框架或对话框使用.

一个简单的例子是:

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

public class AnimationSSCCE extends JPanel
{
    public AnimationSSCCE()
    {
        JButton button = new JButton("Start Animation");
        button.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                JButton button = (JButton)e.getSource();
                WindowAnimation wa = new WindowAnimation(
                    SwingUtilities.windowForComponent(button) );
            }
        });

        add( button );
    }


    class WindowAnimation implements ActionListener
    {
        private Window window;
        private Timer timer;

        public WindowAnimation(Window window)
        {
            this.window = window;
            timer = new Timer(20, this);
            timer.start();
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            window.setSize(window.getWidth() - 5, window.getHeight() - 5);
//          System.out.println( window.getBounds() );
        }
    }


    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("AnimationSSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new AnimationSSCCE() );
        frame.setSize(500, 400);
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,当winow达到一定的最小尺寸时,你会想要停止计时器.我会把那段代码留给你.