Как я могу прочитать x и y моего кадра в другом классе? java областей - PullRequest
0 голосов
/ 24 апреля 2020

У меня проблема с тем, что я получаю ошибку из этих двух строк

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

            }
        });

    }
}

1 Ответ

1 голос
/ 24 апреля 2020

Вам нужно передать 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());
    }
}
...