bigmac147 bigmac147 - 2 months ago 22
Java Question

Java Error Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

I was am looking for a solution to this error what is written on the console is

Exception in thread "AWT-EventQueue-0" 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)

Here is my code
First Class

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class testing extends JFrame {

private JPanel contentPane;
private testing tes = new testing();
private boolean ranOnce = false;

public testing() {
if (ranOnce = false) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ranOnce = true;
tes = new testing();
tes.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);

JLabel lblTest = new JLabel("Test");
contentPane.add(lblTest, BorderLayout.CENTER);
}
}
}


Second Class

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class Test extends JFrame {

private JPanel contentPane;


public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnTestButton = new JButton("Test Button");
btnTestButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new testing();
}
});
btnTestButton.setBounds(114, 90, 89, 23);
contentPane.add(btnTestButton);
}
}


I am using the eclipse plugin window builder I know the stack-overflow exception is caused by too much memory use and I thought using if(runOnce = false) it world fix it

Answer

I fixed the error by removing all the runOnce stuff in the testing class and change the button clicked code to

testing s = new testing();
s.setVisible(true);
setVisible(false);
Comments