Search code examples
user-interfacejframejbuttonjcomponent

Java Buttons does not work


I run into a problem, that I really don't know how to probably create a functional buttons in Java Swing GUI ( I guess this is how I should call it). I create a print statement to check whether if my buttons work or not,and it doesn't work.Here is my code.

    import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;


/**
 * Create a JFrame to hold our beautiful drawings.
 */
public class Jan1UI implements ActionListener
{
    /**
     * Creates a JFrame and adds our drawings
     * 
     * @param args not used
     */

        static JFrame frame = new JFrame();
        static JButton nextBut = new JButton("NEXT");
        static NextDayComponents nextDaycomponent = new NextDayComponents();


    public static void main(String[] args)
    {
        //Set up the JFrame

        nextBut.setBounds(860, 540, 100, 40);
        /*nextBut.setOpaque(false);
        nextBut.setContentAreaFilled(false);
        nextBut.setBorderPainted(false);
        */
        frame.setSize(1920, 1080);
        frame.setTitle("Jan1UI demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setVisible(true);
        frame.add(nextBut);
        frame.add(nextDaycomponent);









    }
    public void actionPerformed(ActionEvent e)
      {
        JButton b = (JButton)e.getSource();

        if (b == nextBut)
        {
            System.out.println("ok");
        }

      }
   }
/*static class Butt implements ActionListener
{
}*/

Solution

  • You need to add an action listener to the button, but cant do that in main as it is a static method. Instead, create a constructor to do thework similar to this:

    public class Jan1UI implements ActionListener
    {
      public static void main(String[] args)
      {
        Jan1UI ui = new Jan1UI();
      }
    
      public Jan1UI ()
      {
        JFrame frame = new JFrame();
    
        JButton nextBut = new JButton("NEXT");
        nextBut.setBounds(860, 540, 100, 40);
        nextBut.addActionListener(this);
    
        frame.setSize(1920, 1080);
        frame.setTitle("Jan1UI demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setVisible(true);
        frame.add(nextBut);
      }
    
      public void actionPerformed(ActionEvent e)
      {
        System.out.println("ok");
      }
    }