想要只创建一次对象

时间:2013-09-05 13:51:11

标签: java swing

我编写了这段代码,用于从数据库加载一些字符串。我想将这些字符串设置为GUI中的复选框。此表单有2个名为Next和Previous的按钮。当我选中2个复选框并单击下一个按钮时它将加载其他字符串集。现在,当我单击上一个按钮时,我希望获得具有选定状态的先前选中的复选框。这些复选框是动态创建的。

private void loadAnswers(JPanel jp, String qId) {
    jp.removeAll();
    try {
        List<Question> listQuestion = questionController.performSearch(qId);
        ArrayList<String> answers = new ArrayList<>();
        for (Question question : listQuestion) {
            if (question.getOpA() != null) {
                answers.add("<html>" + question.getOpA().replace("\n", "<br>") + "</html>");
            }
            if (question.getOpB() != null) {
                answers.add("<html>" + question.getOpB().replace("\n", "<br>") + "</html>");
            }
            if (question.getOpC() != null) {
                answers.add("<html>" + question.getOpC().replace("\n", "<br>") + "</html>");
            }
            if (question.getOpD() != null) {
                answers.add("<html>" + question.getOpD().replace("\n", "<br>") + "</html>");
            }
            if (question.getOpE() != null) {
                answers.add("<html>" + question.getOpE().replace("\n", "<br>") + "</html>");
            }
            if (question.getOpF() != null) {
                answers.add("<html>" + question.getOpF().replace("\n", "<br>") + "</html>");
            }
            if (question.getOpG() != null) {
                answers.add("<html>" + question.getOpG().replace("\n", "<br>") + "</html>");
            }
        }
        JCheckBox[] chkBx = new JCheckBox[answers.size()];
        for (int i = 0; i < chkBx.length; i++) {
            chkBx[i] = new JCheckBox();
            chkBx[i].setText(answers.get(i));
            jPanel1.add(chkBx[i]);
        }
        jp.repaint();
        jp.revalidate();
    } catch (RemoteException ex) {
        Logger.getLogger(TestPane.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TestPane.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(TestPane.class.getName()).log(Level.SEVERE, null, ex);
    }
}

1 个答案:

答案 0 :(得分:4)

为文本框组织存储(最好存储模型 - 文本框值)。我会建议一张地图。当您必须移动到下一页时,请浏览所有复选框并将值放在Map中。返回页面后,再次从地图中提取值并设置复选框的状态。

Key可以是答案的文本,如果它是唯一的,或者是来自问题字段的字符串'(question.getOpE())

相关问题