因此,我一直在为学校项目开发一款小型游戏(只是从Swing GUI开始),并且我有一个名为Background的类,除非在设置菜单中更改分辨率,否则该类将一直保持打开状态。
在设置菜单中,创建具有新分辨率的Background类的新实例。
问题是,我不确定这样做时如何处置旧的Background实例。
这是背景类:
package hangman;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Scanner;
import javax.swing.JFrame;
public class Background extends javax.swing.JFrame {
private int width = 1920;
private int height = 1080;
private String resolution;
private String screenSize;
public Background(String constrScreenSize) {
initComponents();
screenSize = constrScreenSize;
getDefaultRes();
if(screenSize.equals("Fullscreen")) {
setToFullscreen();
}
else {
setToWindowed();
}
}
public Background(String constrScreenSize, String constrResolution) {
initComponents();
screenSize = constrScreenSize;
resolution = constrResolution;
parseResolution(resolution);
if(screenSize.equals("Fullscreen")) {
setToFullscreen();
}
else {
setToWindowed();
}
}
public Background() {
initComponents();
setToFullscreen();
}
//Sets the size of the background to exactly the size of the screen
public void setToFullscreen() {
dispose();
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
}
public void setToWindowed() {
dispose();
setSize(width, height);
setUndecorated(false);
}
public void parseResolution(String res) {
Scanner scanRes = new Scanner(res).useDelimiter(" ");
width = scanRes.nextInt();
scanRes.next();
height = scanRes.nextInt();
}
public void getDefaultRes() {
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
width = (int) screenDimension.getWidth();
height = (int) screenDimension.getHeight();
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Background().setVisible(true);
}
});
}
然后我在 Settings类
中调用其构造函数private void acceptSettingsButtonActionPerformed(java.awt.event.ActionEvent evt) {
new Background(screenSizeSettingComboBox.getSelectedItem().toString(), resolutionSettingComboBox.getSelectedItem().toString()).setVisible(true);
}
很显然,这随后创建了所述Background类的新实例。问题是,我现在只剩下两个实例,而我只想要一个新实例。
最简单的方法是什么?
感谢您的帮助。