0

我在我的 Gui Builder JFram Class A 中使用 Custome jPanel,我面临的问题是当我单击 JFrame 中的按钮时更新我的​​ JPanel 中的组件(Lable)。这里是 Gui Builder JFrame ClassA 中的按钮:它改变了Jpl 的颜色并删除所有标签但不更新新标签。

private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 10; ++idx) {
                q = randomGenerator.nextInt(100);
            }
            jpl1.removeAll();
            new Jpl().printMe(ClassA.q);
            jpl1.revalidate();
            jpl1.setBackground(Color.BLUE);
            jpl1.repaint();
}

这是在 GuiBuilder JFrame Class A 中用作自定义组件的 Jpl 类。

public class Jpl extends JPanel {

public Jpl() {
    printMe(ClassA.q);
}


public void printMe(int q) {

    for (int i = 0; i <q; i++) {
        System.out.println(i+"rinting lable");
        String htmlLabel = "<html><font color=\"#A01070\">" + i + " New Lable </font></html>";
        JLabel lbl = new JLabel(htmlLabel);
        setLayout(new GridLayout(0, 1));
        add(lbl, Jpl.RIGHT_ALIGNMENT);
        lbl.setForeground(Color.BLUE);
        Border border = BorderFactory.createLineBorder(Color.lightGray);
        lbl.setBorder(border);
        lbl.add(new JSeparator(SwingConstants.HORIZONTAL));

        lbl.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                JLabel label = (JLabel) e.getSource();
                JOptionPane.showMessageDialog(null, "You Slected");
                System.out.println(label.getText() + "NO AKKA is Selected");
            }
        });
    }

}
4

1 回答 1

2

您正在 Jpl 的新实例上调用 printMe(),请尝试:

private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 10; ++idx) {
                q = randomGenerator.nextInt(100);
            }
            jpl1.removeAll();
            jpl1.printMe(ClassA.q); // HERE - REMOVED new and using jpl1 instance
            jpl1.setBackground(Color.BLUE);
            jpl1.revalidate();
            jpl1.repaint();
}

不明白为什么要为随机数循环 10 次。只会保留最后一个结果,也许是你想使用的q += randomGenerator.nextInt(100);。此外,如果它是相同的变量,ClassA.q则应替换为。q

于 2011-02-17T19:24:12.633 回答