所以我需要在" Window"中打开一个JFrame。使用" Louncher"类。 它不起作用,我不知道为什么因为我真的是新的。
所以这是Louncher:
package struktogrammer;
public class Louncher {
public static void main(String[] args) {
Window feld = new Window();
}
}
这是窗口:
package struktogrammer;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Window extends JFrame {
private int width = 1000;
private int hight = 750;
public Window() {
Window frame = new Window();
frame.setTitle("Struktogramm");
frame.setSize(width, hight);
frame.setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
dispose();
System.exit(0);
}
});
}
public Window(int width, int hight) {
this.width = width;
this.hight = hight;
Window frame = new Window();
frame.setTitle("Struktogramm");
frame.setSize(width, hight);
frame.setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
dispose();
System.exit(0);
}
});
}
}
当运行Louncher课程时,我得到5页错误:
Exception in thread "main" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Unknown Source)
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at struktogrammer.Window.<init>(Window.java:15)
at struktogrammer.Window.<init>(Window.java:17)
... (same lign about 1200 times)
at struktogrammer.Window.<init>(Window.java:17)
它接缝我运行无限循环,因为它不能使用构造函数? 请帮忙!
答案 0 :(得分:0)
每次创建新窗口时,都会无限制地创建另一个窗口。您需要在Window对象的构造函数中删除另一个Window对象的创建。
public Window() {
// Window frame = new Window(); <---Remove this
frame.setTitle("Struktogramm");
frame.setSize(width, hight);
frame.setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
dispose();
System.exit(0);
}
});
}
答案 1 :(得分:0)
在Window类中,您将再次创建窗口类框架:
Window frame = new Window();
由于每次调用方法时都不需要在此类中创建框架,因此将其删除。每次创建框架时都在创建一个框架。无限循环。
答案 2 :(得分:0)
创建一个JFrame并在其中添加一个JButton,而不是在按钮中添加动作侦听器,并将此代码添加到其中:
此代码使用按钮创建一个框架,当按下按钮时,将打开新窗口。
public class Example extends JFrame {
public Example() {
super("Title");
setLayout(new FlowLayout());
JButton b = new JButton("Open new Frame");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newWindow nw = new newWindow();
}
});
add(b);
}
}
newWindow代码:
public class newWindow extends JFrame {
newWindow() {
super("title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setVisible(true);
}
}