【问题标题】:I can't modify my JButton after having initialized it in the JPanel在 JPanel 中初始化 JButton 后,我无法修改它
【发布时间】:2022-12-31 19:42:25
【问题描述】:
import javax.swing.;
import java.awt.;

public class Space extends JFrame {
   

    private JButton[][] jb;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Space frame = new Space();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Space() {
         JPanel contentPane=new JPanel();
         contentPane.setLayout(new BorderLayout(0, 0));
         JPanel p=new JPanel();
         contentPane.add(p);

         setContentPane(contentPane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);

        p.setLayout(new GridLayout(20,20));
        jb=new JButton[20][20];
        for(int i=0;i<jb.length;i++) {
            for(int j=0;j<jb[i].length;j++) {
                jb[i][j]=new JButton();
                jb[i][j].setIcon(new ImageIcon(getClass().getResource("i1.jpg")));
                p.add(jb[i][j]);
            }
        }
        JButton b=new JButton();
        b.setIcon(new ImageIcon(getClass().getResource("i2.jpg")));
        jb[10][10]=b; // when i set this cell, when i run, the icon of jb[10][10] didn't modified



    }

}

我尝试修改我的按钮 jb[10][10] 但是当我运行所有按钮时都具有相同的图标,我希望按钮也共享 b 图标的所有值

我使用 gridlayout 创建了一个 20x20 的按钮矩阵。问题出在底部,当我想修改已经初始化的按钮时..

【问题讨论】:

    标签: java swing jpanel awt jbutton


    【解决方案1】:

    在嵌套的 for 循环中:

    p.add(jb[i][j]);
    

    已创建并保存在二维数组中的 JButton 对象正在添加到 JPanel.

    当您稍后更改数组元素在此处引用的对象时:

    jb[10][10]=b;
    

    您对 GUI 已经拥有的 JButton 没有影响,因为您没有更改具有的对象状态已经添加到 JPanel.

    相反,您必须显式更改已存在且已由 JPanel 持有的按钮的状态:

    // JButton b=new JButton();
    // b.setIcon(new ImageIcon(getClass().getResource("i2.jpg")));
    // jb[10][10]=b;
    Icon icon = new ImageIcon(getClass().getResource("i2.jpg"));
    jb[10][10].setIcon(icon); // change the state, not the reference
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多