JLabel图像阵列我试图将相同的jlabel存储图像两次加载到gridlayout面板中,但是不是创建图像的两个实例,而是仅显示一次然后移动图像。如何将件数组中的相同JLabel位置存储到boardLabels数组中的多个JLabel中。谢谢 :)public static JPanel boardPanel = new JPanel(new GridLayout(4, 0));public static JLabel pieces[] = new JLabel[2];private static JLabel[] boardLabels = new JLabel[4];public MainFrame() {
pieces[0] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece1.png"));
pieces[1] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece2.png"));
this.add(boardPanel);
displayGUIboard();}public static void displayGUIboard() {
//ERROR - the label in pieces[0] is not copied into both boardLabels [0] and [1]
boardLabels[0] = pieces[0];
boardLabels[1] = pieces[0];
boardPanel.add(boardLabels[0]);
boardPanel.add(boardLabels[1]);}public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}这有效 boardLabels[0] = new JLabel(pieces[1]);
boardLabels[1] = new JLabel(pieces[1]);当使用ImageIcons时,我想避免这种情况,因为要更新电路板,我必须删除然后重新加载JLabel。我更愿意只更新已加载的标签。编辑 我之前尝试过这个但它抛出一个空指针异常... boardLabels[0].setIcon(pieces[1]);
boardLabels[1].setIcon(pieces[1]);
boardPanel.add(boardLabels[0]);
boardPanel.add(boardLabels[1]);
添加回答
举报
0/150
提交
取消