java编程题,

2025-01-02 23:10:54
推荐回答(1个)
回答1:

import java.awt.*;
import java.awt.event.*;

public class MainAwt implements ActionListener
{
Button[] thrButton = new Button[3];
Frame f = null;
public static void main(String[] args)
{
MainAwt ma = new MainAwt();
ma.init();
}
public void init()
{
f = new Frame("Test");
f.setBounds(100, 100, 300, 200);//设定窗体大小
f.setVisible(true);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
f.dispose();
}
}); //设定点击X关闭窗口

for(int i=0;i<3;i++)
{
thrButton[i] = new Button();//初始化按钮
f.add(thrButton[i]);
thrButton[i].addActionListener(this);//添加监听
}

thrButton[0].setLabel("变红");
thrButton[1].setLabel("变黄");
thrButton[2].setLabel("变蓝");

thrButton[0].setBounds(10, 40, 60, 20);
thrButton[1].setBounds(10, 70, 60, 20);
thrButton[2].setBounds(10, 100, 60, 20);

}

public void actionPerformed(ActionEvent e)
{
if(e.getSource() == thrButton[0])
{
f.setBackground(Color.red);
}
else if(e.getSource() == thrButton[2])
{
f.setBackground(Color.blue);
}
else if(e.getSource() == thrButton[1])
{
f.setBackground(Color.yellow);
}
}
}

刚写的。建议楼主好好研究一下。