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++;
}
}
}