Wolfish Wolfish - 1 month ago 5
Java Question

Hard coded buttons do not appear in design view, or in the running program

Whenever I choose to hard code an object (so far, I have sampled buttons, text fields and comboboxes), it does not appear on the associated form. Is there a separate piece of code that handles this, or can I use the following? Additionally, are layout bonds strictly necessary?

JButton startButton = new JButton("Start for loop ex");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
int start = 1;
int end = 5;
int answer = 0;

for (int i = start; i < end; i++){
answer = answer + i;
}
};


IDEOne showing the entirety of the code:
http://ideone.com/u7CuoG

Answer

I think you only created the button, but forgot to put it in the JFrame.

Assuming that this is a subclass of JFrame, you can do this to add the button to the frame:

this.add(startButton);

Also check if you have called setContentPane. If you have not, the button will fill up the whole frame.

It is only natural that dynamically added buttons don't appear in the design view because it would be very slow to compile and run your code every time you open the design view!

EDIT:

I ran the code you gave me and produced this frame. As you can see, the button is on the frame:

enter image description here