[英]Can I add a component to a specific grid cell when a GridLayout is used?
[英]Unable to add image to specific cell grid for JPanel GridLayout
我有一个具有(5,7)GridLayout的JPanel,我正在尝试将图像添加到特定的网格单元格中,例如:(3,1)。 通过研究 ,我意识到有一种方法可以遵循。
编译源代码
package testing;
import java.io.*;
import java.util.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Testing extends JPanel {
public static class TestPanel extends JPanel {
TestPanel() {
int i = 5; // num of rows
int j = 7; // num of cols
PanelHolder = new JPanel[i][j];
setLayout(new GridLayout(i, j));
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
PanelHolder[m][n] = new JPanel();
add(PanelHolder[m][n]);
}
}
File file = new File("./src/testing/Ace_Club_1_1.png");
File file2 = new File("./src/testing/Ace_Diamond_1_1.png");
try {
image = ImageIO.read(file);
image2= ImageIO.read(file2);
} catch (IOException ie) {
}
ImagePanel ip = new ImagePanel(image);
PanelHolder[3][1].add(ip); // doesnt add according to cell grid coordinates
ImagePanel ip2 = new ImagePanel(image2);
PanelHolder[3][3].add(ip2);
}
JPanel[][] PanelHolder;
JLabel DeckLabel;
JPanel DeckPanel;
ImageIcon Deckimg;
private BufferedImage image;
BufferedImage image2;
}
public static class ImagePanel extends JPanel {
ImagePanel(BufferedImage image) {
this.i = image;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(i, 0, 0, getWidth(), getHeight(), this);
}
BufferedImage i;
}
public static void main(String[] args) {
TestPanel tp = new TestPanel();
JFrame frame = new JFrame();
frame.add(tp);
frame.pack();
frame.setVisible(true);
}
}
由于某些未知的原因,我无法将图像添加到特定的单元格中,并且出现在错误的网格单元中,我也无法添加多个图像。
您可以从这里下载图像
编辑:编辑源代码以包括安德鲁·汤普森答案添加多个1图像,但仍然无法正常工作
这是在Andrew Thompson的建议下添加第二张图像后的输出
ImagePanel ip = new ImagePanel(image);
PanelHolder[3][1].add(ip); // doesnt add according to cell grid coordinates
PanelHolder[3][3].add(ip); // only 1 image appears
1个组件只能出现在GUI中的一个位置。 如果需要显示2,请创建2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.