2016-06-19 54 views
0

我遇到了一个问题,我真的不知道如何在Java Swing GUI中创建一个功能按钮(我想这应该称为它)。我创建了一个打印语句来检查我的按钮是否工作,并且它不起作用。这里是我的代码。Java按钮不起作用

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

回答

0

你需要一个动作侦听器添加到按钮,但不能这样做,在主要因为它是一个静态方法。相反,创建一个构造函数来完成与此类似的构造:

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

它看起来像是有效的,除了button但我想我可以自己解决这个问题,非常感谢你的答复,并且给我提供了完整的解决方案。 –

+0

我从示例中删除了'NextDayComponents',因为没有该代码 - 但是假设将填写主要区域 – lostbard

0

必须绑定一个ActionListener添加到按钮:

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

谢谢,但你能告诉我应该在哪里做? –

+0

异常在线程“主要” java.lang.Error的:未解决的问题,编译: \t不能Jan1UI.main(Jan1UI.java:41) –

+0

在静态情况下 \t使用此见我的编辑,右后'nextBut。 setBounds(...'。可能你应该重构你的代码,有很多Swing的例子可以解释这种常见的风格 – PeterMmm