用Java创建一个Button

时间:2014-02-03 20:46:56

标签: java actionlistener

我对编程很新,因为我只是在高中的计算机科学课上。我想到了创建一个基本上模拟国际象棋游戏的国际象棋程序的想法。要做到这一点,我想我会让用户点击他们想要移动到的地方。

我已经浏览了整个互联网,包括java的API,我发现了一些非常有用的信息。然而,在所有这些之后,我仍然对所有不同的方法和类以及用于在Java中创建和使用Buttons的接口感到困惑。虽然这不是关于代码的问题(对不起),但我想知道是否有人知道任何适合我的情况的教程。我正在寻找的东西可以告诉我如何创建和使用一个简单的功能按钮。最好是,如果它描述了所有方法,那么我真的很了解我在做什么。

再次,抱歉这不是关于代码的问题。我想不出一个比Stack Overflow更好的地方来问这个问题所以请不要低估这个“问题”。

谢谢

3 个答案:

答案 0 :(得分:2)

这是一个完全自包含的示例(包含一些代码注释以帮助您了解正在发生的事情):

//Here I am using Swing and AWT (a rather standard way to manage UI elements in Java though technically not the only way)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

//Here is a base class that extends JFrame, JFrames are containers for Swing UI widgets that are represented as windows when executed
public class ButtonExample extends JFrame {
  private static final long serialVersionUID = 1L;

  public static void main(String[] args) {
    //Creatign the frame
    ButtonExample frame = new ButtonExample();
    //Creating the button with the label "Click me!"
    JButton button = new JButton("Click me!");
    //Adding an action listener so we can assign some logic to be executed when this button is clicked on (this is using an anonymous inner class in future versions of Java this will be replaced by the MUCH cleaner Lamba approach, keep an eye out for that)
    button.addActionListener(new ActionListener() {
      //Keep a variable to store how many times the button is clicked.  This shows that the action listener stays running in between clicks)
      private int count = 0;
      //While technically optional thew @Override annotation helps if you update interfaces, get into the habit of doing this to make future work easier, things like Eclipse will insert it for you
      @Override
      public void actionPerformed(ActionEvent e) {
        //Bump up the count variable
        this.count++;
        //And print it to System.out
        System.out.println("Pressed "+this.count + " times");
      }
    });
    //Add the button (with it's listener) to the frame
    frame.add(button);
    //Tell Swing to resize the frame to fit the requested size of all of it's contained widgets
    frame.pack();
    //Tell Swing to show the frame
    frame.setVisible(true);
  }
}

答案 1 :(得分:1)

尝试:

JButton button = new JButton("Click me");

button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        //Do what you like here after button is clicked, for example:
        System.out.println("Button clicked");
    }
});

someJPanel.add(button);

要进行此类应用 - 您将需要大量的知识。它也应该看起来不错,所以很多用Java工作的图形。

答案 2 :(得分:0)

请尝试阅读此文档:Here You Are

在那里,您可以下载,启动示例,这样您就可以看到,尝试每个按钮..