I'm an amateur writing an archery score card. The programme works well but at the cost of 19 sections of identical code each of 18 lines. I'm trying to condense the code by using a method call. I'm using Java SE6 and Mig Layout
Here is the section of code in the GUI which works. The GUI is called as below
HomePage (containing the main method) -> ChoiceGUI -> buildScoresPanel
public void buildScoresPanelMIG(JPanel scoresPanel) {
for (row = 0; row<(int)numberofrows; row++){
scoresPanel.add(scorelabel1[row],"gapleft 0,w 35px, hmin 35px,split 18");
scoresPanel.add(scorelabel2[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel3[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel4[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel5[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel6[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
//another 12 Jlabels }
}
If, however I put the code in a method and call it as below the Jlabels won't show even though I've tried revalidate() repaint() and setVisible(true)
public void buildScoresPanelMIG(JPanel scoresPanel) {
for (row = 0; row<(int)numberofrows; row++){
addScoreLabels();
}
}
public void addScoreLabels(){
scoresPanel.add(scorelabel1[row],"gapleft 0,w 35px, hmin 35px,split 18");
scoresPanel.add(scorelabel2[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel3[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel4[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel5[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
scoresPanel.add(scorelabel6[row],"gap before 0px,gapleft 0,w 35px, hmin 35px");
//another 12 labels
//scoresPanel.revalidate();
//scoresPanel.repaint();
//scoresPanel.setVisible(true);
}
I have trawled the internet for quite a while trying to solve the problem and I realise that I have a fundamental misunderstanding of how Swing components work and would be grateful if someone could explain.
Try passing scoresPanel
as an argument to your addScoreLabels()
method too:
addScoreLabels(scoresPanel);
...
public void addScoreLabels(JPanel scoresPanel) { ...
As Chris Cooney points out in the comments, you probably have a different panel stored in a scoresPanel
field variable, which is being hidden by a local variable in the first method, but not in the second.