I am trying to make a simple GUI, but am running into some errors. I want to create 3 simple buttons, and have them display side by side, the length of the screen. How would I go about doing this ?
My code so far is :
public static void main(String[] args) {
JFrame frame = new JFrame ("JFrame");
JPanel panel = new JPanel( );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
JButton buttons[] = new JButton[2];
for(int i = 0;i<=buttons.le开发者_开发问答ngth ; i++){
panel.add(buttons[i]);
}
frame.getContentPane( ).add( panel );
frame.setSize( 500, 500);
frame.setVisible( true );
}
Hm, if I recall, arrays of objects in Java are initialized with null references. So, in your for, you're adding null to the panel.
You would have to do this:
JButton buttons[] = new JButton[2];
for(int i = 0;i < buttons.length ; i++){
buttons[i] = new JButton(/* whatever */);
panel.add(buttons[i]);
}
Then again, this raises a question: why use an array of buttons if you can just add them as you create them?
You need to initialize the buttons in the array first. You can do that like in the following example.
JButton buttons[] = new JButton[2];
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton("" + i);
}
for(int i = 0; i < buttons.length; i++){
panel.add(buttons[i]);
}
The problem is that all of your buttons get initialized to null
initially. And components don't let you add null
to them.
You need to initialize your buttons before adding them to the panel.
for(int i = 0;i<buttons.length ; i++){
buttons[i] = new JButton();
panel.add(buttons[i]);
}
Also, take note of the modification I made to the for loop i < buttons.length
instead of i <= buttons.length
Here is a nice little example using various JButtons (here). It includes adding ImageIcons to the buttons as well. i.e. An error button.
URL imgURL = JButtonDemo.class.getResource("Error.jpg");
ImageIcon icon = new createImageIcon(imgURL ); // should check that imgURL is not null
buttons[0] = new JButton("Error!",icon);
This makes them a bit more useful than a default JButton
精彩评论