JAVA Swing 图片按钮布局

时间:2023-01-28 14:42:09
package elts.ui;

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;

public class MenuFrame extends JFrame {
public MenuFrame(){
init();
}
private void init(){
setTitle("在线评测");
setSize(600,400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//添加主面板
setContentPane(createContentPane());
}
//创建主面板
private JPanel createContentPane(){
JPanel p=new JPanel(new BorderLayout());
p.add(BorderLayout.NORTH,
createImagePane());
p.add(BorderLayout.CENTER,
createCenterPane());
p.add(BorderLayout.SOUTH,
new JLabel("版权所有 盗版必究",JLabel.RIGHT));
return p;
}
//创建中间部分的面板
private JPanel createCenterPane() {
JPanel p=new JPanel(new BorderLayout());
info=new JLabel("欢迎***参加考试",JLabel.CENTER);
p.add(BorderLayout.NORTH,info);
p.add(createMenuPane());
return p;
}
//创建菜单所在的窗格
private JPanel createMenuPane() {
JPanel p=new JPanel();
JButton start=createImageButton("开始","exam.png");
p.add(start);
JButton result=createImageButton("分数","result.png");
p.add(result);
JButton message=createImageButton("规则","message.png");
p.add(message);
JButton exit=createImageButton("离开","exit.png");
p.add(exit);
return p;

}
//辅助方法,用于创建图像按钮
private JButton createImageButton(
String text,String image){
ImageIcon icon=new ImageIcon(
getClass().getResource(image));
JButton btn=new JButton(text,icon);
btn.setHorizontalTextPosition(
JButton.CENTER);
btn.setVerticalTextPosition(
JButton.BOTTOM);
return btn;
}
private JPanel createImagePane() {
JPanel p=new JPanel();
ImageIcon icon2=new ImageIcon(
getClass().getResource("title.png"));
p.add(new JLabel(icon2));
return p;
}
//定义私有属性
private JLabel info;
//main方法
public static void main(String[] args) {
MenuFrame menu=new MenuFrame();
menu.setVisible(true);
}
}