如何在另一个类中更新JFrame?

时间:2014-01-07 02:23:40

标签: java swing jframe

我想在构造函数或其他类中更新已创建的Control的JLabel。在这里,我创建了一个Control并在Constructor中添加了一些组件。 UI是在main中创建的,但我想更新此类之外的一些标签。所以我创建了setResult(最终的String文本,最终的String路径)来做这样的事情,但是它没有用....

public class Control extends JFrame
{

private static Control control;
static HashMap<String, JLabel> results = new HashMap<String, JLabel>();
public Control(ArrayList<TestCase> tests)
{
    super("WFC Tests");
    setLayout(new GridLayout(tests.size() + 1, 6));

    start.addActionListener(bl);
    JComboBox comBox = new JComboBox(testCategoties);
    loopsField.setText("1");

    JPanel jp = new JPanel();
    jp.setLayout(new FlowLayout());
    jp.add(comBox);
    jp.add(loops);
    jp.add(loopsField);
    jp.add(mainDevice);
    jp.add(mainDeviceText);
    jp.add(refDevice1);
    jp.add(refDeviceText1);
    jp.add(refDevice2);
    jp.add(refDeviceText2);
    jp.add(start);

    add(jp);

    for (TestCase test : tests)
    {
        add(createPane(test));
    }
}
private JPanel createPane(TestCase test)
{
    JPanel jp = new JPanel();
    test.getIterationTextField().setText("0");
    test.getCallTextField().setText("0");
    test.getHoldTextField().setText("0");

    jp.setLayout(new FlowLayout(FlowLayout.LEFT));
    test.getTestCheckBox().setPreferredSize(new Dimension(200, 20));
    jp.add(test.getTestCheckBox(), (int) JCheckBoxMenuItem.CENTER);

    jp.add(test.getLogCheckBox(), JCheckBoxMenuItem.CENTER_ALIGNMENT);
    jp.add(test.getIterationLabel());
    jp.add(test.getIterationTextField());

    if (test.getName().contains("Call"))
    {
        jp.add(test.getCallLabel());
        jp.add(test.getCallTextField());
    }

    if (test.getName().contains("Hold"))
    {
        jp.add(test.getHoldLabel());
        jp.add(test.getHoldTextField());
    }

    test.getResultLabel().setBackground(Color.LIGHT_GRAY);
    test.getResultLabel().setOpaque(true);
    jp.add(test.getResultLabel(), JPanel.RIGHT_ALIGNMENT);
    results.put(test.getPath(), test.getResultLabel());
    return jp;
}
public static void run(final JFrame f, final int width, final int height)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            f.setTitle(f.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(width, height);
            f.setVisible(true);
        }
    });
}
public static void main(String[] args) 
{
    testCases = SanityTest.getSanityTestCases();
    control = new Control(testCases);
    run(control, 1000, 800);

}

我的问题是setResult无效。我不知道为什么。有人可以帮忙吗?谢谢!

public void setResult(final String text, final String path)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            results.get(path).setText(text);
        }
    });
    control.getContentPane().validate();
}
}

1 个答案:

答案 0 :(得分:0)

我认为问题出在control.getContentPane().validate();尝试添加control.repaint();