A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 张海涛 于 2013-1-19 16:43 编辑

import javax.swing.*; import java.awt.event.*; public class TestJavax extends JFrame implements ActionListener { JButton a=new JButton(); JButton b=new JButton(); JButton c=new JButton(); JPanel x=new JPanel(); public TestJavax() { a.setText("你好"); this.setBounds(500,200,300,200); this.setTitle("窗口"); this.setVisible(true); this.add(x); x.add(a); a.addActionListener(this); } public void actionPerformed(ActionEvent e) { a.setVisible(false); b.setText("HELLO"); this.setBounds(500,200,300,200); this.setVisible(true); this.setTitle("窗口2"); x.add(b); b.addActionListener(this); //问题在这里,当点击上面的“你好”按钮的时候,会出现下面的这里的“HELLO”按钮。 //但是我想继续当点这个“HELLO”的时候,能够再生成一个“你好-HELLO”的按钮,也就是处理actionPerformed方法里面的 //内容,应该如何做? } public static void main(String args[]){ TestJavax a=new TestJavax(); } }

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1 赞一个!

查看全部评分

1 个回复

倒序浏览
本帖最后由 黑马张英涛 于 2013-1-19 08:43 编辑

你可以采用这个办法:将按钮的名字保存在一个数组中,每次调用actionPerformed都重新生个一个button对象,然后将名字改为数组中的值,如下
  1. import javax.swing.*;
  2. import java.awt.event.*;

  3. public class TestJavax extends JFrame implements ActionListener {
  4.         JButton a = new JButton();
  5.         JPanel x = new JPanel();
  6.         String[] str = { "你好", "hello", "你好-hello" };
  7.         int i = 1;

  8.         public TestJavax() {
  9.                 a.setText(str[0]);
  10.                 this.setBounds(500, 200, 300, 200);
  11.                 this.setTitle("窗口" + i);
  12.                 this.setVisible(true);
  13.                 this.add(x);
  14.                 x.add(a);
  15.                 a.addActionListener(this);
  16.         }

  17.         public void actionPerformed(ActionEvent e) {
  18.                 if (i >= str.length)  //由于字符串数组只有3个元素,所以这里判断一下,否则str[i++]会出现角标越界
  19.                         System.exit(1);
  20.                 a.setVisible(false);
  21.                 a = new JButton(str[i++]);
  22.                 a.setVisible(true);
  23.                 this.setTitle("窗口" + i);
  24.                 x.add(a);
  25.                 a.addActionListener(this);
  26.         }

  27.         public static void main(String args[]) {
  28.                 TestJavax a = new TestJavax();
  29.         }
  30. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马