java - 如何點擊按鈕,重新運行(我是初學者)?
問題描述
下面是我全部的代碼:
package day0411;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.*;import java.util.Random;/** * Created by Administrator on 2017-4-11. */public class Farme1 { public static void main(String[] args) {//創建窗口對象Frame f1 = new Frame();Button btn = new Button('OOO!');f1.setVisible(true);//顯示窗口對象。f1.setBounds(200,500,550,350); //設置位置f1.setTitle('我的窗口程序!'); //設置窗口標題。f1.setIconImage(Toolkit.getDefaultToolkit().getImage('F:L-我的圖片logoeyes-1059234.jpg'));//設置窗體左上角圖標f1.setLayout(null);//制作界面時用的的布局函數btn.setBackground(Color.gray);btn.setSize(50, 30);btn.setLocation(10,30);btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {NewButton(f1); }});f1.add(btn);CloseFrame(f1); } public static void CreatFrame(Frame f1,Button btn){ } public static int Random1(){//隨機函數生成0-255之間的數字、Random rd = new Random();int a= rd.nextInt(256);return a; } public static void NewButton(Frame f1){int x = 50;int y= 100;int count = 0;for (int i=0;i<9;i++){ Button bt1 = new Button('BT'+(i+1)); //隨機顏色。 bt1.setBackground(new Color(Random1(),Random1(),Random1())); bt1.setBounds(x, y, 50, 30); f1.add(bt1); x+=60; count++; if (count==3){y += 50;count =0;x=50;//System.out.println('AAAA'); } try {Thread.sleep(200); } catch (InterruptedException e1) {e1.printStackTrace(); }} } public static void CloseFrame(Frame f1){f1.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) {System.exit(0); }}); }}
我想到的是
boolean a =false;if(!a){ ... a=flase;}else{ ... a=true}"但是這樣好像并不對。。
問題解答
回答1:可以使用一個 List 保存當前已經存在的 顏色隨機的Button,然后每次點擊按鈕,都先將 Frame 上面在該 List 中的 Button 去掉。
/** * 用來保存那些顏色隨機的 Button */static java.util.List<Button> newButtons = new ArrayList<>();public static void NewButton(final Frame f1) { // 每次添加之前,先移除原來的顏色隨機按鈕 for (Button button : newButtons) {f1.remove(button); } int x = 50; int y = 100; int count = 0; for (int i = 0; i < 9; i++) {Button bt1 = new Button('BT' + (i + 1));//隨機顏色。bt1.setBackground(new Color(Random1(), Random1(), Random1()));bt1.setBounds(x, y, 50, 30);f1.add(bt1);x += 60;count++;if (count == 3) { y += 50; count = 0; x = 50; //System.out.println('AAAA');}newButtons.add(bt1); // 將 bt1 加入 newButtonstry { Thread.sleep(200);} catch (InterruptedException e1) { e1.printStackTrace();} }}
