Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
After I moved the JFrame things from a driver to Drum.java, it stopped working.
code:

public class Drum extends JFrame {
	private JButton hihat,snare,tom1,tom2,base,floortom, ridecymbal,crashcymbal;
	private JLabel label1,label2,label3,label4,label5,label6,label7,label8,label9,part1,part2,part3,part4,part5,part6,part7,part8;
	private ImageIcon I1,I2,I3,I4,I5,I6,I7,I8;
	private JPanel p1,p2;
	public Drum(){
		//Adds a new JFrame
		  JFrame frame= new JFrame("Drumset");
      // So that when you x the GUI, the program will close.
		  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		  Drum panel2 = new Drum();
      // initalizes the contents of frame.
		  frame.getContentPane().add(panel2);
		   // so the frame can be visible.
		  frame.setVisible(true);
		// makes the frame fit the size of the contents
		  frame.pack();
		  // makes the frame visible.
		  frame.setVisible(true);
		 
		  
		//creates the panel
		p1= new JPanel();
		//creates the buttons
	hihat= new JButton();
	// sets button to an image
hihat.setIcon(new ImageIcon("Snare.PNG"));
// adds button to panel
p1.add(hihat);
// adds panel
add(p1);</pre>
}
}


What I have tried:

I have tried moving the Jframe things to the bottom and doing this:
public static void main(String[]
args){
<pre>  JFrame frame= new JFrame("Drumset");
      // So that when you x the GUI, the program will close.
		  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		  Drum panel2 = new Drum();
      // initalizes the contents of frame.
		  frame.getContentPane().add(panel2);
		   // so the frame can be visible.
		  frame.setVisible(true);
		// makes the frame fit the size of the contents
		  frame.pack();
		  // makes the frame visible.
		  frame.setVisible(true);

}
}
}
Posted
Updated 18-May-20 14:08pm
v2
Comments
Richard MacCutchan 19-May-20 3:47am    
You are creating local variables (frame, panel etc.) inside the Drum constructor. So as soon as the constructor code ends all those variable go out of scope and are garbage collected. If you want them to last for the duration of the application then they need to be declared at class level.
Tornado 9000 20-May-20 17:29pm    
How would I declare the frame, panels, Jbuttons, and JLabel in the class level?
Richard MacCutchan 21-May-20 4:42am    
The same way you would for any class level variables. If you still do not really understand classes, objects, scope rules etc, then I suggest you go to The Java™ Tutorials[^] for some excellent tutorials.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900