【发布时间】:2016-10-16 16:48:41
【问题描述】:
我正在尝试将图像添加到 Jbuttons。这些图像位于我使用单独的类创建的数组中。每次添加图像的尝试都失败了。我试图将它们变成 ImageIcon 并按原样添加它们,但它不起作用。第一组代码是我用来创建按钮并添加到 JFrame 的代码。我的目标是添加事件侦听器,以便在按下按钮时按钮将显示图像、矩形或带有文本的矩形
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonTest extends JFrame{
public ButtonTest(){
JPanel panel = new JPanel();
JButton[] b = new JButton[9];
Image[] imgs = MyImageSplit.splitter("dog", 9);
for (int i=0; i<b.length; i++){
b[i]=new JButton();
b[i].setPreferredSize(new Dimension(100, 100));
panel.add(b[i]);
}
add(panel);
setVisible(true);
setSize(400,400);
}
public static void main(String[] args) {
new ButtonTest();
}
}
这段代码是我用来分割图像并将较小的图像添加到数组中的代码。
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import javax.imageio.ImageIO;
public class MyImageSplit {
public static Image[] splitter (String filename, int numGroup){
int rows=(int) Math.sqrt(numGroup);
int cols=(int) Math.sqrt(numGroup);
BufferedImage[] buffimage = new BufferedImage[rows*cols];
Image[] images = new Image[rows*cols];
try{
File file = new File(filename + ".jpg"); //gets image from directory
FileInputStream f = new FileInputStream(file);
BufferedImage img = ImageIO.read(f); //reads the image file
//determines the width and height for each piece
int pieceWidth=img.getWidth()/cols;
int pieceHeight = img.getHeight()/rows;
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
//Initialize the image array with image pieces
buffimage[x * rows + y] = new BufferedImage(pieceWidth, pieceHeight, img.getType());
// draws the image piece
Graphics2D gr = buffimage[x * rows + y].createGraphics();
gr.drawImage(img, 0, 0, pieceWidth, pieceHeight, pieceWidth * y, pieceHeight * x, pieceWidth * y + pieceWidth, pieceHeight * x + pieceHeight, null);
gr.dispose();
}
}
for (int i =0; i < buffimage.length; i++){
ImageIO.write(buffimage[i], "jpg", new File(filename + i + ".jpg"));
}
}
catch (Exception e) {
System.out.println(e.getStackTrace());
}
for(int i = 0; i < rows*cols; i++){
images[i] = (Image) buffimage[i];
}
return images;
}
public static void main(String[] args){
splitter("monkey", 9);
}
}
【问题讨论】:
-
你检查过图片加载是否正确吗?尝试使用简单的代码在 JFrame 上使用带有 JLabel 的 ImageIcon。