2016-06-19 236 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