1

I am new to Java and I am creating a simple GUI. I have a label in Java in a JFrame, and when I click it, the program is supposed to show another frame and to hide the current one. I make it print as well to check whether the label (which acts like a button) works. The first time it does not work at all. It works the in the next attempts starting from the second click but it does not hide the current frame.

My code is:

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {                                     

    MainFrame mf = new MainFrame();
    jLabel4.addMouseListener(new MouseAdapter (){

        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("It works.");
            mf.setVisible(true);

            NewJFrame2 n2 = new NewJFrame2();
            n2.setVisible(false);

        }          
    });

Does anyone know how to fix it in order to work from the first click and hide the current frame?

Frakcool
  • 10,915
  • 9
  • 50
  • 89
Danny
  • 369
  • 2
  • 3
  • 11
  • 2
    The logic shown in the uncompilable code snippet above is deeply messed up. All the code statements in the `mousePressed` method whould be moved to the same method of the 'parent' listener. General tips: 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 3) 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). 4) .. – Andrew Thompson Jun 05 '17 at 13:57
  • 3
    .. 4) `NewJFrame2` use **descriptive** names for attributes and classes, rather than the robot-like suggestions of the IDE. – Andrew Thompson Jun 05 '17 at 13:59

4 Answers4

6

Instead of clicking on a JLabel why not create a JButton which already handles clicks with an ActionListener and make it look like a JLabel as shown in the multiple answers on this question.

but it does NOT hide the current JFrame

Well, you need to call JFrame#dispose() method on your listener, but also please take a look at The Use of Multiple JFrames: Good or Bad Practice?, it's better to use a Card Layout or maybe take a look at the tutorial on How to use Dialogs

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • I am using a label because I need to have an image. – Danny Jun 05 '17 at 14:07
  • 2
    A button can have an image too: For [example](https://stackoverflow.com/questions/4801386/how-do-i-add-an-image-to-a-jbutton) or the [tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html) example :) So, my answer is still valid :D – Frakcool Jun 05 '17 at 14:14
0

Use n2.dispose() instead n2.setVisible(false);

This is a simple example for you but as others said multiple JFrame in same application is not good. Rather than try one JFrame and JPanel with with a appropriate layout.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
    JFrame MainFrame;
    JFrame ChildFrame;
    JLabel label;

    public Main(){
        MainFrame = new JFrame("Example");
        MainFrame.setSize(300, 300);

        label = new JLabel("Click me");
        labelMousePressed();
        MainFrame.add(label);
        MainFrame.setVisible(true);
    }
    private void labelMousePressed() {                                     
        label.addMouseListener(new MouseAdapter(){

            public void mousePressed(MouseEvent e){
                System.out.println("It works.");

                MainFrame.dispose();

                ChildFrame = new JFrame("Child");
                ChildFrame.setSize(300, 300);
                ChildFrame.setVisible(true);
            }          
        });
    }
    public static void main(String[] args) {
        Main m = new Main();
    }
}

UPDATE

If you donot override the methods in JFrame, it is unnecessary to extends(inherit) JFrame class. Rather than that create a object from JFrame and use it. read this question to learn more about this.

Blasanka
  • 21,001
  • 12
  • 102
  • 104
  • What is the difference ? – Samuel Owino Jun 05 '17 at 14:19
  • @samuelowino: Calling `dispose()` frees the resources associated – Blasanka Jun 05 '17 at 14:46
  • 1
    I add the items manually and I used the code starting from "private void labelMousePressed()" and I seem to have an issue. It doesn't work the first time, then the second it prints once, the third prints two times and so on. – Danny Jun 05 '17 at 14:48
  • Try my example. – Blasanka Jun 05 '17 at 14:49
  • 1
    @Danny this is because on each click of the button the print "it works" statement is executed that's what happens in itsactionListener block, on each click of the UI component the code block in its actionListsner call is executed – Samuel Owino Jun 05 '17 at 14:52
0

Java Labels are not capable of receiving ActionListener event, you should replace the label with a button. You don't click on labels you click on button, what could work for the label probably would be a property change listeners.

Run and analysis this code it will clearly guide you... and good luck you chose the best language in the world, am a java guy two

class MainFrame extends JFrame {

JButton button2 = new JButton("Go to Frame 2");


public MainFrame() {
    setSize(500, 500);
    getContentPane().setBackground(Color.RED);
    setLayout(new FlowLayout());

    add(button2);

    button2.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            setVisible(false);
            new Sample2().setVisible(true);
        }
    });
}}


public class Sample2 extends JFrame {

JButton button4;

public Sample2() {

    setSize(500, 600);
    setLayout(new FlowLayout());
    getContentPane().setBackground(Color.YELLOW);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainFrame mf = new MainFrame();
    button4 = new JButton("Button 4");
    add(button4);

    button4.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("It works.");
            mf.setVisible(true);
            setVisible(false);
        }
    });
}
public static void main(String[] args) {
    Sample2 sample2 = new Sample2();
    sample2.setVisible(true);
}}
Samuel Owino
  • 747
  • 1
  • 12
  • 24
  • I saw early that you chose a JLabel because you need an image, you can also achieve this with a JButton. Check out the code in my next edit – Samuel Owino Jun 05 '17 at 14:20
  • You are welcome @Danny, just a suggestion try covering Manning Up Swing In Action, Core Java 2 and Java The Complete Reference Books for a deeper understanding of swing UI programming. They worked for me. – Samuel Owino Jun 05 '17 at 14:30
0

Java Labels are not capable of receiving ActionListener event, you should replace the label with a button. You don't click on labels you click on button, what could work for the label probably would be a property change listeners.

In this answer the Buttons have images, Just remember to create a folder unser src name it res then add the images you the button to display. You can replace the image file names with my file names in

//new ImageIcon(getClass().getResource("/res/image-file_name"));**

package StackOverflowProblemSets;

import sun.applet.Main;

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

/**
 * Created by HACKER on 05/06/2017.
 * https://stackoverflow.com/questions/44370545/mouselistener-doesnt-work-
   the-first-time-and-there-are-other-errors
 */

class MainFrame extends JFrame {

    JButton button2 = new JButton("Go to Frame 2", new 
ImageIcon(getClass().getResource("/res/ic_action_maps_blue.png")));


public MainFrame() {
    setSize(500, 500);
    getContentPane().setBackground(Color.RED);
    setLayout(new FlowLayout());

    add(button2);

    button2.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            setVisible(false);
            new Sample2().setVisible(true);
        }
    });}}



public class Sample2 extends JFrame {

JButton button4;

public Sample2() {

    setSize(500, 600);
    setLayout(new FlowLayout());
    getContentPane().setBackground(Color.YELLOW);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MainFrame mf = new MainFrame();
    button4 = new JButton("Button 4", new 
ImageIcon(getClass().getResource("/res/ic_action_alpha_icon_D.png")));
    add(button4);

    button4.addMouseListener(new MouseAdapter() {
        /**
         * {@inheritDoc}
         *
         * @param e
         */
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("It works.");
            mf.setVisible(true);
            setVisible(false);
        }
    });
}

public static void main(String[] args) {
    Sample2 sample2 = new Sample2();
    sample2.setVisible(true);
}}
Samuel Owino
  • 747
  • 1
  • 12
  • 24