-1

I am trying to enter an event for JButon I create:

    JButton botton1=new JButton("welcom to my show db! lets start");
    botton1.setFont(new Font ("Eras Medium ITC",Font.BOLD,20));
    this.add(botton1);

    JPanel Basic_panel=new JPanel();
    Basic_panel.setName("SHOW DB ");
    Basic_panel.setBounds(x,y,width,hight);

    botton1.addActionListener(this) ;
}
          public void actionPerformed(ActionEvent e) {
                if (e.getSource()==botton1){

Now I want to enter another JFrame I made, and make the first disappear. How?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DANA
  • 1
  • 2
  • Possible duplicate of [Opening a new JFrame and close previous after clicking button](http://stackoverflow.com/questions/28860914/opening-a-new-jframe-and-close-previous-after-clicking-button) – ArcticLord Jan 06 '16 at 13:21
  • 1
    Please explain what you really want. You want to hide/dispose the frame which shows the button, that has started the action? – Sergiy Medvynskyy Jan 06 '16 at 13:53
  • 2
    *"now i want to enter another jframe i made and make the first disappear."* 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Instead use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). 3) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Jan 06 '16 at 15:26

1 Answers1

3

For your original question:

How to add action to a button?

you might want to check How to write an Action Listener.

For your second question:

Now I want to enter another JFrame I made, and make the first disappear. How?

please check both approaches :)

Option 1 (Recommended)

If you want to do it the right way, you should use a CardLayout as recommended by @AndrewThompson in his comment above.

I also saw you were using a Null Layout (because of setBounds() method), you might also want to get rid of it, see Why is it frowned upon to use a null layout in Swing? and Null Layout is Evil to know why, insted you should be using a Layout Manager or combinations of them as shown in the following code based on @AndrewThompson's answer (The same that was linked in his comment above) but a bit modified to work with a JFrame instead of a JOptionPane, so give him credit by upvoting his Original Answer too!

This produces the following outputs:

enter image description here enter image description here

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

class CardLayoutDemo {
    JButton button1, button2;

    CardLayoutDemo() {
        JFrame gui = new JFrame("CardLayoutDemo");
        button1 = new JButton("Go to pane 2");
        button2 = new JButton("Go to pane 1");
        JPanel pane1 = new JPanel();
        pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS));
        JPanel pane2 = new JPanel();
        pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
        final CardLayout cl = new CardLayout();
        final JPanel cards = new JPanel(cl);

        pane1.add(new JLabel("This is my pane 1"));
        pane1.add(button1);
        
        pane2.add(new JLabel("This is my pane 2"));
        pane2.add(button2);

        gui.add(cards);
        cards.add(pane1, "frame1");
        cards.add(pane2, "frame2");

        ActionListener al = new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
                if (ae.getSource() == button1) {
                    cl.show(cards, "frame2");
                } else if (ae.getSource() == button2) {
                    cl.show(cards, "frame1");
                }
            }
        };

        button1.addActionListener(al);
        button2.addActionListener(al);
        
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.pack();
        gui.setVisible(true);
    }
    public static void main(String[] args) {
        new CardLayoutDemo();
    }
}

With this option you only have 1 JFrame but you can change through different views, and you don't annoy user with multiple windows on the task bar.

One more tip here is: If you're going to open this second JFrame to prevent user from doing something on the 1st one, you should consider using a JOptionPane or this second JFrame will contain just a bit information which you don't want to have there for the whole time (Something like a pop up).


Option 2 (Not recommended)

But if you really really really want to use multiple JFrames (which is not recommended) you can dispose() it. At the time you're calling your new JFrame to be created. For example, the following code produces this output:

enter image description here enter image description here

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TwoJFrames {
    JFrame frame;
    JButton button;

    TwoJFrames() {
        frame = new JFrame("1st frame");
        button = new JButton("Click me!");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new AnotherFrame();
                frame.dispose();
            }
        });

        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        new TwoJFrames();
    }

    class AnotherFrame {
        JFrame frame2;
        JLabel label;
        AnotherFrame() {
            frame2 = new JFrame("Second Frame");
            label = new JLabel("This is my second frame");

            frame2.add(label);
            frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame2.pack();
            frame2.setVisible(true);
        }
    }
}

In this case you might want to consider setVisible() instead if you want to go back to previous state or reopen this one when closing the second JFrame


Both of my above codes are called a Minimal, Complete, and Verifiable example (MCVE) or Runnable Example or Short, Self Contained, Correct Example (SSCCE) which are code you can copy-paste and see the same output as me, when you have an error in your code, these examples are very handy because we can see where your errors are or be able to find them easier and/or faster.

You should consider reading all the links I provided (included these ones) and for your future questions to make something like I've done above, that way you'll prevent confusion and you'll get more, faster and better responses.

Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • thank you,i did axactaly as the option 1..its good.but ,why when i tryed to save the fram2 as a private in the first one and call it in the method it didnt work??and only when i call a new one ? – DANA Jan 06 '16 at 16:53
  • one more question..how exactly i add a file of picture??and where do i keep it in the java ecalipse??? – DANA Jan 06 '16 at 16:54
  • That's another question and you should ask another question for that. But before you should [Google it](https://www.google.com.mx/search?client=ubuntu&channel=fs&q=eclipse+java+import+image&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=8kaNVrmQMvKosATp6ZCACQ) and the 1st result will guide you to [this question](http://stackoverflow.com/questions/5657469/how-do-i-go-about-adding-an-image-into-a-java-project-with-eclipse). If you don't find it at google, then and only then, come and ask here with what you have tried, not backwards. – Frakcool Jan 06 '16 at 16:57
  • See also this [Google search](https://www.google.com.mx/search?client=ubuntu&channel=fs&q=java+insert+image&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=hUeNVrTCKqqhsAT1ub6oBg#channel=fs&q=java+insert+image) on How to insert an Image in Java. Which most likely will guide you to: [How to insert an image into a JPanel](http://stackoverflow.com/questions/299495/how-to-add-an-image-to-a-jpanel) or use the [search tool](http://stackoverflow.com/search?q=) from Stack Overflow. – Frakcool Jan 06 '16 at 16:59
  • @DANA *why when i tryed to save the fram2 as a private in the first one and call it in the method it didnt work?? ...* what you mean? I'm confused. Try to be more clear when asking, your questions are a bit broad and don't help us to understand what your problem is – Frakcool Jan 06 '16 at 17:00
  • @DANA I don't see any private variable there. Could you [edit](http://stackoverflow.com/posts/34633999/edit) your question (Don't delete anything, just add it below), as I said before, as an [MCVE](http://stackoverflow.com/help/mcve) might be the best idea. – Frakcool Jan 06 '16 at 17:05
  • private JFram fram2 setTitle("SHOW DB "); int x=400,y=200,width=400,hight=400; setBounds(x,y,width,hight); JButton botton1=new JButton("welcom to my show db! lets start"); botton1.setFont(new Font ("Eras Medium ITC",Font.BOLD,20)); this.add(botton1); JPanel Basic_panel=new JPanel(); Basic_panel.setName("SHOW DB "); Basic_panel.setBounds(x,y,width,hight); botton1.addActionListener(this) ; } public void actionPerformed(ActionEvent e) { this.dispose(); fram2.setvisible(true); } } – DANA Jan 06 '16 at 17:06
  • There's no `JFram` class in Java, it's `JFrame` again please [edit](http://stackoverflow.com/posts/34633999/edit) your question and add an [MCVE](http://stackoverflow.com/help/mcve) following **ALL** my above recommendations (from Null Layout to Card Layout or Dispose) otherwise I can't help you. – Frakcool Jan 06 '16 at 17:08