问题出在update()方法中,使用removeAll()将原有的组件移除后,没有重新设置scene的大小和位置。因此,在切换场景后,scene组件的大小和位置仍然是之前的大小和位置,导致第二个按钮没有立即出现。

要解决这个问题,可以在switchScene()方法中重新设置场景的大小和位置,或者在update()方法中重新设置scene的大小和位置。

以下是修改后的代码:

//File Window.java package com.sen.superswing;

import javax.swing.; import java.awt.; import java.util.Timer; import java.util.TimerTask;

public class Window extends JFrame { protected Scene scene = new Scene(); protected Timer timer; public Window() { super(); Container container = this.getContentPane(); container.add(scene); scene.setBounds(0,0,this.getWidth(),this.getHeight()); enableUpdate(); } public Window(String title) { super(title); Container container = this.getContentPane(); container.add(scene); scene.setBounds(0,0,this.getWidth(),this.getHeight()); enableUpdate(); } public void switchScene(Scene scene) { Container container = this.getContentPane(); container.removeAll(); container.add(scene); this.scene = scene; scene.setBounds(0,0,this.getWidth(),this.getHeight()); // 添加这一行代码 this.repaint(); } public void update() { this.removeAll(); this.add(scene); scene.setBounds(0,0,this.getWidth(),this.getHeight()); // 添加这一行代码 } protected void enableUpdate() { timer = new Timer(); Window window = this; TimerTask task = new TimerTask() { @Override public void run() { if (!window.isVisible()) timer.cancel(); else window.update(); } }; timer.schedule(task,100); } }

经过修改后,按钮在关闭对话框后,第一个按钮会消失,第二个按钮会立即出现

请判断为什么以下代码没有达到我想要的效果怎么解决在点击第一个按钮并关闭对话框后第1个按钮消失了第2个按钮没有立即出现而是在最大化最小化后出现:File Startjavapackage comsensuperswing;import javaxswing;import javaawt;public class Start public static void mainString args

原文地址: http://www.cveoy.top/t/topic/iMjY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录