首页 > 解决方案 > 如何在另一个班级中读出我的框架的 x 和 y?java范围

问题描述

我的问题是我从这两行中得到一个错误

System.out.println(tw.getX());
System.out.println(tw.getY());

因为范围tw不对。如何正确设置?

package misc;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import static java.awt.GraphicsDevice.WindowTranslucency.*;

public class TranslucentJframe extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private JButton button;

    public TranslucentJframe() {
        super("Frame");
        setLayout(new GridBagLayout());

        setSize(485,860);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        button = new JButton("Frame is set!");
        button.addActionListener(new SetFrame());

        this.getContentPane().add(button);
    }

    public class SetFrame implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            System.out.println(tw.getX());
            System.out.println(tw.getY());

        }

    }

    public static void main(String[] args) {
        // Determine if the GraphicsDevice supports translucency.
        GraphicsEnvironment ge = 
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();

        //If translucent windows aren't supported, exit.
        if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
            System.err.println(
                "Translucency is not supported");
                System.exit(0);
        }

        JFrame.setDefaultLookAndFeelDecorated(true);

        // Create the GUI on the event-dispatching thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TranslucentJframe tw = new TranslucentJframe();

                // Set the window to 55% opaque (45% translucent).
                tw.setOpacity(0.55f);

                // Display the window.
                tw.setVisible(true);

            }
        });

    }
}

标签: javascope

解决方案


您需要将 传递给TranslucentJframe侦听SetFrame器。

改变button.addActionListener(new SetFrame());

对此button.addActionListener(new SetFrame(this));

然后在 中定义字段SetFrame

public class SetFrame implements ActionListener {
    private TranslucentJframe tw;

    public SetFrame(TranslucentJframe tw) {
        this.tw = tw;
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println(tw.getX());
        System.out.println(tw.getY());
    }
}

推荐阅读