两种读图的方法
Image grass=new ImageIcon("pure-grass.gif").getImage();
Image img=Toolkit.getDefaultToolkit().getImage("board.jpg");
让屏幕大小区匹配图片
bg=new ImageIcon("board1.jpg");
JLabel lable=new JLabel(bg);
imagePanel=(JPanel)getContentPane();
//设置为透明
imagePanel.setOpaque(false);
imagePanel.setLayout(null);
lable.setBounds(0,0,bg.getIconWidth(),bg.getIconHeight());
getLayeredPane().add(lable,new Integer(Integer.MIN_VALUE));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(bg.getIconWidth(), bg.getIconHeight());
还有另一种方法,就是让图片伸展
附上带菜单和背景的完整代码
package fiveChess;
import java.awt.Button;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
//import chessTest.ChessBoard;
public class MainFrame extends JFrame{
private ChessBoard chessBoard;
private JMenuBar menubar;
private JMenu sysmenu;
private JMenuItem startMenuItem,exitMenuItem,backMenuItem;
private Image bg;
public MainFrame() throws HeadlessException {
super("五子棋");
//Container container=getContentPane();
Dimension dimension=new Dimension(500, 500);
setSize(dimension);
setLocation(400,150);
chessBoard=new ChessBoard();
Container contentpane=this.getContentPane();
//contentpane.add(chessBoard);
Lis lis=new Lis();
menubar=new JMenuBar();
sysmenu=new JMenu("菜单");
startMenuItem=new JMenuItem("重新开始");
exitMenuItem=new JMenuItem("退出");
backMenuItem=new JMenuItem("悔棋");
startMenuItem.addActionListener(lis);
exitMenuItem.addActionListener(lis);
backMenuItem.addActionListener(lis);
sysmenu.add(startMenuItem);
sysmenu.add(exitMenuItem);
sysmenu.add(backMenuItem);
menubar.add(sysmenu);
setJMenuBar(menubar);
bg=new ImageIcon("board1.jpg").getImage();
ImageIcon imageIcon=new ImageIcon(bg);
JLabel lable=new JLabel(imageIcon);
lable.setBounds(0, 0, dimension.width, dimension.height);
getLayeredPane().add(lable,new Integer(Integer.MIN_VALUE));
JPanel jp=(JPanel)this.getContentPane();
jp.setOpaque(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class Lis implements ActionListener{
public void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if(obj==startMenuItem){
System.out.println("重新开始");
}
else if(obj==exitMenuItem){
System.out.println("退出");
}
else if(obj==backMenuItem){
System.out.println("悔棋");
}
}
}
public static void main(String[] args){
MainFrame mainframe=new MainFrame();
}
}