java试图在多个JPanel中显示图像
我正在创建一个以12 JPanels
网格为特色的程序。按下"add image"
按钮时,网格中的第一个JPanel
中会出现一个图像,并且计数器会递增一。从那时起,每次再次单击"add image"
时,一个图像将被添加到下一个JPanel
。出于某种原因,该按钮只会在第一个JPanel
中添加一个图像,然后停止工作。这是我目前掌握的代码
public class ImageGrid extends JFrame {
static JPanel[] imageSpaces = new JPanel[12];
int imageCounter = 0;
ImageGrid() {
this.setTitle("Image Grid");
setSize(750, 750);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(3, 4, 10, 5));
p3.setBackground(Color.WHITE);
p3.setOpaque(true);
p3.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
for (int j = 0; j < imageSpaces.length; j++) {
imageSpaces[j] = setImageSpace();
p3.add(imageSpaces[j]);
}
MyButtonPanel p1 = new MyButtonPanel();
add(p1, BorderLayout.SOUTH);
add(p3, BorderLayout.CENTER);
}
public JPanel setImageSpace() {
JPanel test;
test = new JPanel();
test.setOpaque(true);
test.setPreferredSize(new Dimension(100, 100));
return test;
}
class MyButtonPanel extends JPanel implements ActionListener {
final JButton addImage = new JButton("Add Image");
ImageIcon lorryPicture = new ImageIcon(ImageGrid.class.getResource("/resources/lorry.png"));
JLabel lorryImage = new JLabel(lorryPicture);
MyButtonPanel() {
add(addImage);
addImage.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addImage) {
imageSpaces[imageCounter].add(lorryImage);
revalidate();
repaint();
imageCounter++;
}
}
}
public static void main(String[] args) {
ImageGrid test = new ImageGrid();
test.setVisible(true);
}
}
# 1 楼答案
您应该重新验证并重新喷涂面板(即受添加影响的集装箱),而不是框架
Diclaimer:这可能是一个简单的修复,但也要注意,一个组件(在本例中是
JLabel lorryImage
)只能有一个父容器。上述修复仍然有效的原因是,您没有重新验证并重新绘制标签添加到的上一个面板。因此,您可能需要考虑正确地执行此操作,并在每个面板中添加一个new JLabel
免责声明2:您应该添加一个检查,仅当计数小于数组长度时才添加标签,以避免
ArrayIndexOutOfBoundsException
旁注
Swing应用程序应该从事件调度线程(EDT)运行。可以通过将代码包装在
main
中的SwingUtilities.invokeLater(...)
中来实现这一点。详见Initial Threads你也可以用
JLabel
来调用setIcon
,而不是用JPanel