我正在尝试简化 Javax swing 图形类,以便其他人更容易进入 Java 图形,但我在测试它时遇到了问题。请记住,我是作为代码用户而不是开发人员编写 main 方法。我需要能改变类方法代码而不是主要方法的答案。我的主要方法代码应该做的是当用户将鼠标悬停在按钮上时打印“悬停”。但是,当我在 if 语句之前添加一个 SOP 语句时,它可以工作......鼠标悬停的方法在 Button 类中。这是我的主要方法代码 - public static void main(String[] args) { GraphWin win = new GraphWin(1000, 1000, "Graphics Window - Test"); win.show(); Button button = new Button(new Point(380, 300), new Point(620, 400)); button.draw(win); enter code herewhile(true) { //System.out.println(button.hovering); if(button.hovering) { System.out.println("hovering"); } } }这是我的 Button 类代码 -public class Button implements MouseListener{ public JButton button; public boolean clicked = false, hovering = false, pressed = false; public Button(Point p, Point p2) { //This is the default constructor of the button with only 2 points specified this.button = new JButton(); this.setBounds(p, p2); this.button.addMouseListener(this); this.setBorderVisible(false);} public Button(Point p, Point p2, String text) { //This constructor requires text to be displayed`enter code here` this.button = new JButton(text); this.setBounds(p, p2); this.button.addMouseListener(this); this.setBorderVisible(false);} public Button(String icon, Point p, Point p2) { //This constructor sets an Icon for the button this.button = new JButton(); this.setIcon(icon); this.setBounds(p, p2); this.button.addMouseListener(this); this.setBorderVisible(false);} }
2 回答

拉莫斯之舞
TA贡献1820条经验 获得超10个赞
这种事情通常与线程有关。
Swing 中的事件在 AWT 事件调度线程 (EDT) 上调度。为了线程安全,几乎所有处理 Swing/AWT 的事情都应该在 EDT 上完成。
在您的情况下,设置和读取的变量之间没有任何锁定。添加 aprintln会导致暂停(带有各种内存障碍或诸如此类),这恰好允许程序以所需的顺序运行。
您可能已经看到main将执行直接传递给 AWT 的方法。
class MyGUI {
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(MyGUI::go);
}
private static void go() {
...
最好自己提供主类,实现它以应用程序类作为参数,并在一切设置好后继续执行。虽然传统命令行使用main静态方法/函数,但在其他任何地方都使用子类型:Applet、Servlet 等。

PIPIONE
TA贡献1829条经验 获得超9个赞
最好的方法是使用一种isHovering()
方法,但对while(true)
有或没有 Sysout 内部行为的有根据的猜测可能与编译器优化有关。可以通过将悬停变量设置为来修复transient
添加回答
举报
0/150
提交
取消