我正在尝试将图像添加到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);
}
}
答案 0 :(得分:2)
您忘记为每个按钮添加图片。将其添加到您的for-loop
:
for (int i=0; i<b.length; i++){
b[i]=new JButton();
b[i].setPreferredSize(new Dimension(200, 100));
b[i].setIcon(new ImageIcon(imgs[i]));
panel.add(b[i]);
}
此外,我建议您更改JButton
首选尺寸,因为图片不适合它们。
b[i].setPreferredSize(new Dimension(200, 100));
以及JFrame
的大小。
setSize(800,400);
编辑:使用.png
图像文件扩展名来正确保持颜色。 .jpg
会导致一些颜色的损失。比较:
<强> dog.jpg 强>
<强> dog.png 强>
答案 1 :(得分:0)
看起来您创建了按钮但从未设置过图像。
将以下行添加到ButtonTest
中的主循环中:
b[i].setIcon(new ImageIcon(imgs[i]));