Java按钮不起作用

时间:2016-06-19 09:27:33

标签: user-interface jframe jbutton jcomponent

我遇到了一个问题,我真的不知道如何在Java Swing GUI中创建一个功能按钮(我猜这就是我应该怎么称呼它)。我创建了一个print语句来检查我的按钮是否有效,并且它不起作用。这是我的代码。

    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
{
}*/

2 个答案:

答案 0 :(得分:0)

您必须将ActionListener绑定到按钮:

nextBut.setBounds(860, 540, 100, 40);
nextBut.addActionListener(new Jan1UI());

答案 1 :(得分:0)

您需要向按钮添加动作侦听器,但不能在main中执行此操作,因为它是静态方法。相反,创建一个构造函数来完成与此类似的工作:

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");
  }
}