java中创建一个按钮组,有10个按钮,分别写着0,1,2,,3。。。。9

Python016

java中创建一个按钮组,有10个按钮,分别写着0,1,2,,3。。。。9,第1张

用Java创建按钮组的程序如下:

import java.awt.GridLayout

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import javax.swing.JButton

import javax.swing.JFrame

public class A extends JFrame implements ActionListener{

 JButton[] b=new JButton[10]

 A(){

  setLayout(new GridLayout(3,4,5,5))

  for(int i=0i<10i++){

   b[i]=new JButton(String.valueOf(i))

   b[i].addActionListener(this)

   add(b[i])

  }

  setSize(300,300)

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

  setVisible(true)

 }

 public static void main(String[] args) {

  new A()

 }

 public void actionPerformed(ActionEvent ae) {

 }

}

使用图形用户界面

class Gui extends JFrame implements ActionListener {

private JButton jb = new JButton()

Gui() {

super("Gui")

this.add(jb) //添加按钮

jb.addActionListener(this) //按钮事件监听

//当然你可以按自己的想法做布局

this.pack()

this.setVisible(true)//可见

this.setResizable(false)//不可修改大小

this.setLocation(100, 100)//起始位置

}

//覆写ActionListener接口中的事件处理方法

@Override

public void actionPerformed(ActionEvent e) {

if(e.getSource() == jb) {

//事件处理

}

}

}