My program is supposed to launch a second JFrame and print a statement when the button is clicked, but it always launches three JFrames and prints three statements. I need it to only print out one statement and launch one Jframe. Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
@SuppressWarnings("serial")
public class Test extends JPanel implements ActionListener {
JButton button = new JButton();
String buttonString = "Buttontext";
public Test() {
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
button.setText("Buttontext");
button.setCursor(Cursor.getDefaultCursor());
button.setMargin(new Insets(0, 0, 0, 0));
button.setBounds(700, 400, 100, 20);
button.setActionCommand(buttonString);
button.addActionListener(this);
this.add(button);
}
public static void createandshowGUI() {
JFrame frame = new JFrame("Frame");
frame.getContentPane().setBackground(Color.white);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(dim.width, dim.height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Test());
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createandshowGUI();
}
});
}
public void actionPerformed(ActionEvent e) {
if (buttonString.equals(e.getActionCommand())) {
System.out.println("creating a new frame");
newframe();
}
}
public void newframe() {
JFrame frame2 = new JFrame();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame2.setSize(dim.width / 2, dim.height / 2);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame2.setVisible(true);
}
}