图形化界面处理

运用BorderLayout编写一个简单小游戏程序。EAST CENTER NORTH

package day14;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class RoleSelector extends JFrame{
    /** 角色图片标签 **/
    private JLabel lbRoleImage;
    /** 角色属性值 **/
    private JLabel[] lbValue;
    private String[][] strArr = {
            {"100","100","100","100","100"},
            {"200","200","200","200","200"},
            {"300","300","300","300","300"},
            {"400","400","400","400","400"},
            {"500","500","500","500","500"}
    };
    public RoleSelector(){
        JPanel pnBasic = new JPanel();
        pnBasic.setLayout(new BorderLayout());
        // 角色选择区
        String[] strArrRoleName = {"Goddess","Assassin","Death","Garuda","Captain"};
        JComboBox cbRoleName = new JComboBox(strArrRoleName);
        cbRoleName.addActionListener(new SelectMonitor());
        pnBasic.add(cbRoleName,BorderLayout.NORTH);
        // 角色图片区
        lbRoleImage = new JLabel();
        ImageIcon icon = new ImageIcon("assets/role/Goddess.png");
        lbRoleImage.setIcon(icon);
        pnBasic.add(lbRoleImage,BorderLayout.CENTER);
        // 角色属性区:
        JPanel pnRoleAttr = new JPanel();
        pnRoleAttr.setLayout(new GridLayout(5,2,5,5));
              
        String[] strTitle = {"HP:","MP:","AP:","DP:","EXP:"};
        JLabel[] lbTitle = new JLabel[5];
        lbValue = new JLabel[5];
        for(int i=0;i<lbTitle.length;i++){
            lbTitle[i] = new JLabel(strTitle[i]);
            lbValue[i] = new JLabel(strArr[0][i]);
            pnRoleAttr.add(lbTitle[i]);
            pnRoleAttr.add(lbValue[i]);
        }
              
        pnBasic.add(pnRoleAttr,BorderLayout.EAST);
              
        // 绑定
        setContentPane(pnBasic);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("登陆");
        // setSize  setLocation
        setBounds(200,200,400,300);
//      pack();
        // 窗体可见
        setVisible(true);
    }
          
    // 下列列表的监听
    private class SelectMonitor implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            // 获得选项的名字
            String strSelectName = (String) cb.getSelectedItem();
            // 获得选项的下标
            int index = cb.getSelectedIndex();
            ImageIcon icon = new ImageIcon("assets/role/"+strSelectName+".png");
            lbRoleImage.setIcon(icon);
            pack();
            for(int i=0;i<lbValue.length;i++){
                lbValue[i].setText(strArr[index][i]);
            }
        }
    }
          
    public static void main(String[] args) {
        new RoleSelector();
    }
}

你可能感兴趣的:(小游戏)