5

プログラムでボタンを押すと、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

           }

        }
    });

しかし、問題はここ「これ」にあり、JFrame を参照していません。また、JFrame の新しいオブジェクトを作成することさえできません。別のウィンドウが表示されるためです。誰かがこの問題を解決するのを手伝ってくれますか?

4

2 に答える 2

5

試す

int width = Foo.this.getWidth();

FooサブクラスJFrame. _

于 2011-08-07T15:12:46.850 に答える
5

プログラムでボタンを押したときにJFrameをアニメーション化して半分のサイズにしたい

したがって、ボタンをクリックすると、ボタンにアクセスできます。次に、次を使用できます。

SwingUtilities.windowForComponent( theButton );

フレームへの参照を取得します。

したがって、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();
            }
        });
    }
}

もちろん、ウィンドウが特定の最小サイズに達したときにタイマーを停止する必要があります。そのコードはあなたに任せます。

于 2011-08-07T15:14:29.343 に答える