我有一个问题,我从这两行中得到一个错误

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

            }
        });

    }
}

最佳答案

您需要将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());
    }
}

07-24 16:34