7

I need program - main JFrame have 2 buttons

  1. button
  2. button2

When I click button it has to open new JFrame window with new options, while if I click button2 then open another window.

In these 2 new windows I must add buttons like next and previous.

I have a problem, when I open button 1 , then open 2 windows and main JFrame still be visible.

My first program on swing:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class example {

public static void main (String[] args){    
  JFrame frame = new JFrame("Test");
  frame.setVisible(true);
  frame.setSize(500,200);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  JPanel panel = new JPanel();
  frame.add(panel);
  JButton button = new JButton("hello agin1");
  panel.add(button);
  button.addActionListener (new Action1());

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button.addActionListener (new Action2()); 
}
static class Action1 implements ActionListener {        
  public void actionPerformed (ActionEvent e) {     
    JFrame frame2 = new JFrame("Clicked");
    frame2.setVisible(true);
    frame2.setSize(200,200);
    JLabel label = new JLabel("you clicked me");
    JPanel panel = new JPanel();
    frame2.add(panel);
    panel.add(label);       
  }
}   
static class Action2 implements ActionListener {        
  public void actionPerformed (ActionEvent e) {     
    JFrame frame3 = new JFrame("OKNO 3");
    frame3.setVisible(true);
    frame3.setSize(200,200);

    JLabel label = new JLabel("kliknales");
    JPanel panel = new JPanel();
    frame3.add(panel);
    panel.add(label);
  }
}   
}
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Lukii007
  • 85
  • 1
  • 3
  • 4

1 Answers1

7

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Robin
  • 36,233
  • 5
  • 47
  • 99
  • 3
    The code I posted was copy-pasted from yours, and I only added a `2`. You should be able to do that yourself. And the `invokeLater` call can be copied almost directly from the link I provided – Robin Jan 07 '12 at 18:45
  • I agreed with @Robin just after you declared the button2 on second line it is button.add... instead of button**2**. – Adnan Nov 11 '15 at 08:54