java - 如何在另一个班级中读出我的框架的 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);
}
});
}
}
解决方案
您需要将 传递给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());
}
}
推荐阅读
- mysql - MySQL:使用多个 if 语句触发
- javascript - 使用 React 的 setInterval 动画只发生一次
- actions-on-google - Actions on Google,Actions SDK - 我可以在我的 webhook 响应中使用类型覆盖来创建和更改自由文本类型吗?
- c# - SFTP使用c sharp将列表插入sql数据库表?
- ios - React Native:无法在 AppCenter 中签署 Ad-hoc iOS OneSignal 扩展
- sas - SAS按组识别单品未按预期工作
- python - 展平嵌套的json并在python中获取键和嵌套键
- android - 带有 Realm 数据库的 Dager Hilt
- python - Pymysql在查询中使用变量和列表
- php - api 平台过滤器具有相同属性的多个值