gpt4 book ai didi

java - 我怎样才能在另一个类(class)读出我的框架的x和y? java范围

转载 作者:行者123 更新时间:2023-12-02 08:40:35 25 4
gpt4 key购买 nike

我遇到的问题是这两行出现错误

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

关于java - 我怎样才能在另一个类(class)读出我的框架的x和y? java范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61413778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com