Reputation: 3
I'm having troubles with this program. Everything works, but the program keeps opening the JFrame over and over again (and obviously, I only want just one JFrame to be opened). What is wrong with my code?
Thank you in advance, Stefan
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColoredWords {
JFrame frame;
JPanel controlPanel, wordsPanel;
JButton match, nomatch;
ColoredWords() {
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
frame = new JFrame("Colored Words Experiment");
wordsPanel = new JPanel();
controlPanel = new JPanel();
frame.setLayout(new BorderLayout());
frame.add(wordsPanel, BorderLayout.NORTH);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.setSize(1000, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
match = new JButton("Matching");
nomatch = new JButton("Non-Matching");
controlPanel.add(match, BorderLayout.WEST);
controlPanel.add(nomatch, BorderLayout.CENTER);
ClicksReporter clicksreporter;
clicksreporter = new ClicksReporter();
match.addActionListener(clicksreporter);
nomatch.addActionListener(clicksreporter);
}
} );
}
class ClicksReporter extends ColoredWords implements ActionListener {
Labeling labeling = new Labeling();
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Matching")) {
wordsPanel.add(labeling);
} else if (e.getActionCommand().equals("Non-Matching")) {
wordsPanel.add(labeling);
}
}
}
public static void main(String[] arg) {
new ColoredWords();
}
}
class Labeling extends JPanel {
JLabel[] labelsList = new JLabel[20];
int i = 0;
public Labeling() {
while (i < 5) {
labelsList[i] = new JLabel("black");
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
labelsList[i].setOpaque(true);
labelsList[i].setBackground(Color.white);
add(labelsList[i]);
i++;
}
}
}
Upvotes: 0
Views: 214
Reputation: 59113
JFrame
in your ColoredWords
constructor.ClicksReporter
in your ColoredWords
constructor.ClicksReporter
extends ColoredWords
.That means every ColoredWords
construction leads to another ColoredWords
construction, which also creates a JFrame
.
Upvotes: 0
Reputation: 2223
Your ColoredWords
constructor calls clicksreporter = new ClicksReporter();
but ClicksReporter
inherits ColoredWords
, so the constructor of ColoredWords
gets called, wich will again execute clicksreporter = new ClicksReporter();
and so on... You get stuck in an infinite loop. Try to remove inheritance.
Upvotes: 0
Reputation: 2907
The problem is when you instantiate ClicksReporter
inside main()
. This is because it inherits the constructor of ColoredWords
, calling it when instantiated. To avoid this, you can take the program code out of the constructor and into another method, say, execute()
or run()
. You can then adjust your program accordingly to call this method in main()
.
Upvotes: 1