Jump to content

Need help with button with image

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Serialcek

Serialcek

    Learning Programmer

  • Members
  • PipPipPip
  • 72 posts
Hello everyone..
This is a piece of code which cause me problems.. i hope it's enough code to understand my problem.


		frame.setLayout(new GridLayout(s, d));

		grid = new JButton[d][s];


		for (int x = 0; x < d; x++) {

			for (int y = 0; y < s; y++) {


			//	grid[x][y] = new JButton(img);  THIS WORKS BUT PUT AN IMAGE EVERYWHERE


				frame.add(grid[x][y]);

				grid[x][y].setText("ola");

				grid[x][y].setHorizontalTextPosition(JButton.CENTER);

				grid[x][y].setVerticalTextPosition(JButton.CENTER);

				grid[x][y].setBorder(null);

			

			}

		}

		

//		grid[5][5].setIcon(img);  I WOULD LIKE TO DO SOMETHING LIKE THIS BUT IT GIVES ME NULLPOINTEREXEPTION 



So I created a grid layout and then I want to put an image on some of the button which I added on the grid.
Thx for help and have a nice day :)

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
setIcon is the way to go,
You can get a nullpointer if in the loop condition d and s are smaller or equal to 5 (they must be at least 6 to fill up grid[5][5])
Or you can get a nullpointer if in the loop you don't do new JButton()

#3
Serialcek

Serialcek

    Learning Programmer

  • Members
  • PipPipPip
  • 72 posts
Hmm so the condition that d and s are smaller or equal to 5 is false because d and s are 15.
But yes now I just take another look in the my code because you set : if in the loop you don't do new JButton()
And I found a problem. I forgot to uncomment this:

				grid[x][y] = new JButton();


Thank you very much Wim Dc :)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users