Why doesn’t my button event start in Swing?

Asked

Viewed 49 times

1

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;

public class main{

    public static void main(String[] args){
        JFrame frame = new JFrame();
        JButton bo = new JButton("Clique");
        frame.add(bo);
        frame.setSize(600,600);
        frame.setVisible(true);

    }

    private void bo(java.awt.event.ActionEvent evt) {
        JFrame a = new JFrame();
        a.setVisible(true);
        a.setSize(900,900);


    }

}

Guys, why is my button event not working? it even compiles, but when I click on the "click" button it nn opens the other window I asked to open;-;

  • and where did you associate an event click on the button to make it work? is missing this

  • can you give me an example of what I should do?

  • need to add a "Switch" to "listen" to the button events, in this case the click: bo.addActionListener(new ActionListener()
{
 public void actionPerformed(java.awt.event.ActionEvent evt) { ...seu codigo aqui.... } }

1 answer

0


Good night!

I took your code and made the button "listen" to the action, with a LAMBDA expression simplified some lines, making it work...

private static javax.swing.JButton bo;

public static void main(String[] args){
    JFrame frame = new JFrame();
    bo = new javax.swing.JButton("Clique");
    frame.add(bo);
    frame.setSize(600,600);
    frame.setVisible(true);
    bo.addActionListener((java.awt.event.ActionEvent evt) -> {
        JFrame a = new JFrame();
        a.setVisible(true);
        a.setSize(900,900);
    });

}

In short you were not making your button "listen" to the action that was done... I hope you understand what I mean!!

  • mt thanks, helped me mt!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.