1、确定窗口的图片(java自带,可查阅包装文档翻看如何调用)
2、设置窗体大小不可更改(同样时Java自带的方法,无需编写)
3、读取电脑屏幕的尺寸,使窗口位于屏幕正中央
4、增加东、西、南、北、中五个按钮,中按钮增加图片
5、设置事件监听器和事件源,使得点击按钮时出现变化
package com.yc.frame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyFrame extends JFrame{
JButton btn[]=new JButton[5];//定义了5个按钮 btn[0]=null...btn[4]=null
Container cont=this.getContentPane();//得到窗体的内容面板
private class MyActionListener implements ActionListener{
/**
* 创建一个事件监听器
*/
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("东")) {
btn[1].setBackground(Color.black);
JOptionPane.showMessageDialog(cont, "你点击了东");//点击后显示弹窗
}else
if(e.getActionCommand().equals("西")) {
btn[2].setBackground(Color.GREEN);
JOptionPane.showMessageDialog(cont, "你点击了西");
}else
if(e.getActionCommand().equals("南")) {
btn[3].setBackground(Color.gray);
JOptionPane.showMessageDialog(cont, "你点击了南");
}else
if(e.getActionCommand().equals("北")) {
btn[4].setBackground(Color.cyan);
JOptionPane.showMessageDialog(cont, "你点击了北");
}else
if(e.getActionCommand().equals("中")) {
btn[0].setBackground(Color.yellow);
JOptionPane.showMessageDialog(cont, "你点击了中");
}
}
}
/**
* 不带惨的构造方法
*/
public MyFrame() {
super("我的第一个窗体");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口
this.setBackground(Color.BLUE);//设置背景色
btn[0]=new JButton("中",new ImageIcon("jin.jpg"));//实例化一个按钮
btn[1]=new JButton("东");
btn[2]=new JButton("西");
btn[3]=new JButton("南");
btn[4]=new JButton("北");
cont.add(btn[0],BorderLayout.CENTER);
cont.add(btn[1],BorderLayout.EAST);
cont.add(btn[2],BorderLayout.WEST);
cont.add(btn[3],BorderLayout.SOUTH);
cont.add(btn[4],BorderLayout.NORTH);
MyActionListener m1=new MyActionListener();
/**
* 事件源
*/
for(int i=0;i<5;i++)
btn[i].addActionListener(m1);
//得到一个照片
Image img=Toolkit.getDefaultToolkit().getImage("jin.jpg");
//设置一下窗体的图标
this.setIconImage(img);
this.setResizable(false);//设置窗体大小不可更改
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();//读取电脑屏幕的尺寸大小
//设置窗口的大小
this.setSize((int)screenSize.getWidth()/2,(int)(screenSize.getHeight())/2);//设置窗体的大小
this.setLocation(((int)screenSize.getWidth()-this.getWidth())/2,((int)(screenSize.getHeight())-this.getHeight())/2);//设置位置位于正中间
this.setVisible(true);//让窗体可以显示出来
}
public static void main(String []args) {
MyFrame mf=new MyFrame();//实例化了一个大小没有 并且不可见的窗体
}
}
运行结果: