I'm trying to make a simple game which i made array of 9 buttons and for loops to display them and add then to ContentPane.
I'm trying to add images to the buttons in the for loops and I cannot get it to work./ any help?
String[] images = {"rainbow.jpg", "leprechaun.jpg", "potofgold.jpg"}; // IMAGES
// --- ICONS ---
Icon Icon1 = new ImageIcon("rainbow.jpg");
Icon Icon2 = new ImageIcon("leprechaun.jpg");
Icon Iconwin = new ImageIcon("potofgold2.jpg");
Icon blank = new ImageIcon("blank.jpg");
//creates array of buttons called tiles
JButton[] tile = new JButton[9];
They are the arrays and Icons.
for(int i = 0; i < tile.length; i++)
{
contentPane.add(tile[i]);
tile[i].setIcon(images[1]);
tile[i].addActionListener(this);
}
I'm trying to make it random image to the buttons. selects randomly I cannot get it to work I get error on tile[i].setIcon(images[1])
even when trying to just place it the 2nd image it give sme error
method setIcon in class AbstractButton cannot be applied to given types;
tile[i].setIcon(images[1]);
setIcon uses an Icon as its argument rather than a String
tile[i].setIcon(icon1);
Adding the buttons directly would be simpler
getContentPane().add(new ImageIcon(images[i]);
Related
I'm relatively new to java and have been working on a simple Blackjack program using Java Swing, but I'm having trouble getting setAlignmentX to work in OverlayLayout.
Basically the idea is to have two cards generate on the left side of the play area (the red rectangle), then add another card (on top and to the right of the previous cards) when the player clicks "Draw".
Picture Link because I'm too new to Stack Overflow
I try to do this by adding a card (JLabel with image icon) with a .setAlignmentX that is greater than the previous card.
However, there are two problems. The first is that when a single card is generated, it is able to stick all the way to the left of the rectangle. However, when two cards are generated, they both generate further to the right, away from the side.
The second is that the new card is adding itself below, and to the left, of the previous cards (instead of above and to the right). Furthermore, as per the two cards, the whole chunk is moving rightwards on every draw.
Another Picture Link
Here is the relevant code:
ArrayList<JLabel> tuCardsPanelList = new ArrayList<>();
...
for(int i = 0; i < 9; i++){
tuCardsPanelList.add(new JLabel());
}
tuCardsPanel = new JPanel(new BorderLayout());
tuCardsPanel.setBackground(new Color(130, 30, 40));
tuCardsPanel.setBorder(new LineBorder(Color.yellow));
tuCardsPanel.setPreferredSize(new Dimension(400, 200));
tuCardsPanel.setLayout(new OverlayLayout(tuCardsPanel));
...
//display first two cards
ImageIcon image = new ImageIcon(getClass().getResource(activePlayer.hand.get(0).imageLocation));
tuCardsPanelList.get(0).setIcon(new ImageIcon(image.getImage().getScaledInstance(121, 185, Image.SCALE_SMOOTH)));
tuCardsPanelList.get(0).setPreferredSize(new Dimension(121, 185));
tuCardsPanelList.get(0).setAlignmentX(0.0f);//SETALIGNMENTX HERE
tuCardsPanelList.get(0).setAlignmentY(0.5f);
ImageIcon image1 = new ImageIcon(getClass().getResource(activePlayer.hand.get(1).imageLocation));
tuCardsPanelList.get(1).setIcon(new ImageIcon(image1.getImage().getScaledInstance(121, 185, Image.SCALE_SMOOTH)));
tuCardsPanelList.get(1).setPreferredSize(new Dimension(121, 185));
tuCardsPanelList.get(1).setAlignmentX(0.16f); //SETALIGNMENTX HERE
tuCardsPanelList.get(1).setAlignmentY(0.5f);
tuCardsPanel.add(tuCardsPanelList.get(0));
tuCardsPanel.add(tuCardsPanelList.get(1));
...
//when "Draw" button is pressed
activePlayer.drawFrom(deck);
tuLabel3.setText("Total: " + activePlayer.valueOfHand());
int currentNewCard = activePlayer.hand.size() - 1;
ImageIcon image = new ImageIcon(getClass().getResource(activePlayer.hand.get(currentNewCard).imageLocation));
tuCardsPanelList.get(currentNewCard).setIcon(new ImageIcon(image.getImage().getScaledInstance(121, 185, Image.SCALE_SMOOTH)));
tuCardsPanelList.get(currentNewCard).setPreferredSize(new Dimension(121, 185));
tuCardsPanelList.get(currentNewCard).setAlignmentY(0.5f);
tuCardsPanelList.get(currentNewCard).setAlignmentX(0.32f); //SETALIGNMENTX HERE
If it helps, one really weird thing I found was that the second card (with .setAlignmentX(0.16f)) is actually on the left of the first card (which has a .setAlignmentX(0f)!)
I think they are all symptoms of a property of .setAlignmentX or OverlayLayout that I'm misusing, but I just can't figure it out. Google didn't help either.
Any help will be greatly appreciated! :)
I'am trying to do memory game. I have 12 buttons and 6 images.
I want to randomly set the image to the button. One image to 2 buttons.
ImageIcon[] icons = {icon1,icon2,icon3,icon4,icon5,icon6};
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
I know this Random r = new Random(); but no idea how can I use it here.
Edit:
U used this
for (int i = 0; i < buttons.length; i++)
buttons[i].setIcon( iconList.get(i) );
How can I set something like visible(false) of this icon?
Don't have 12 different variable names for your buttons. Instead create an Array to hold your 12 buttons.
Use an ArrayList to contain 12 Icons (two of each image).
Then you can use the shuffle(...) method of the ArrayList to randomly sort the icons.
Then you create a loop to assign each Icon to a button. Something like:
for (int i = 0; i < buttons.length; i++)
buttons[i].setIcon( iconList.get(i) );
Edit:
The above suggestion was to assign the Icons to the button when the button was created.
If you have a game where you have an empty Icon and then you display the Icon when the button is clicked then you need a different approach.
In your ActionListener code you will need to search the button array to see which button was clicked. Once you get the index of this button, then you get the matching Icon:
JButton button = (JButton)event.getSource();
for (int i = buttons.length; i < buttons.length;i++)
{
if (button = buttons[i];
{
button.setIcon( iconList.get(i) );
break;
}
}
The same ActionListener can be used for all buttons since the logic is generic.
I'm trying to make a simple calculator in Java using Swing, and I've created my buttons the following way:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
My question is how do I reference each specific button in my event handler? I can't think of a way to do this without having to manually create each button rather than using a loop.
Thanks.
In your listener, call event.getSource(), and that will return the button which has been pressed. Get the text of the button, and you have its number.
Or create a different instance of your handler for every button, and pass the value of the button (i) to the constructor of the handler. This last solution is cleaner, IMO, because it doesn't depend on the text of the button. If you replaced the text by an image, for example, the first technique wouldn't work anymore.
You can distinguish created buttons by adding the following inside handler:
String buttonText = ((JButton) e.getSource()).getText();
if (<text1>.equals(buttonText)){
//do the stuff
} else if (<text2>.equals(buttonText)){
//do the stuff
} else {
//do the stuff
}
Method #1: go through the child components of the parent JPanel (quite tedious, has to be rebuilt every time you modify the contents of that JPanel). Make sure they're JButtons by using an if . . instanceof clause.
Method #2: as you create them in that loop, add them to a List (or even better, a Map). I prefer a Map personally as it lets me customise the key for that specific JComponent
i.e.
HashMap<String, JComponent> buttonList = new HashMap<String, JComponent>();
for(. .) {
buttonList.put("nameForEachButton", button);
}
I recommend generating the button name based off of the loop counter. Either use your existing name value, or just set it to "button" + i;
Declare your buttons using an array.
JButton[] button = new JButton[9]; //outside the for loop
for (int i = 0; i < 10; i++) {
//put your code
button[i] = new JButton(name);
//your code
}
I'm trying to build an array of JButton images. These will have a toggle (viewable/not viewable) thus why I chose to use JButtons.
These buttons also have a background image. When I place one button to the pane, this is in Java obviously, it works. But when I load the buttons in to an array and try to print them to the pane, nothing....I would appreciate the help. Here's what I have.
JButton card = new JButton();
JButton[] deck = new JButton[9];
int xLoc=20, yLoc=5;
card.setIcon(new ImageIcon("Back.jpg"));
card.setSize(200,250);
card.setVisible(true);
for(int i=0; i<9;i++)
{
deck[i]=card;
}
for(int i=1;i<10;i++)
{
deck[i-1].setLocation(xLoc,yLoc);
pane.add(deck[i - 1]);
validate();
xLoc+=220;
if(i%3==0)
{
yLoc+=265;
}
In my mind, I am creating a card object with a size and a background and visible, and then loading the same card over and over in to my array, then adding it to the pane, that has a background. It's not causing any errors or exceptions, but it's not placing anything but the background to the pane.
Thanks in advance. I will be honest and say this is a homework assignment, but I am exceeding the expectations by going this route. I know I can create individual buttons and put them on the screen. I know how, and can do it. What I want to do is not covered in the scope of the class.
This is a project, not just an assignment, and the instructor encouraged learning new things on our own and expanding the project. So, by helping me you are not helping me cheat, but helping me learn something more than the class teaches. Thanks!
Your basic problem comes down to the fact that a component can only reside within a single parent...
// You create a card...
JButton card = new JButton();
// You create an array of buttons
JButton[] deck = new JButton[9];
int xLoc=20, yLoc=5;
// You set the icon
card.setIcon(new ImageIcon("Back.jpg"));
// This is not a good idea...
card.setSize(200,250);
// JButton is visible by default...
card.setVisible(true);
// Start your loop...
for(int i=0; i<9;i++)
{
// Assign the card reference to an element in the array...
deck[i]=card;
// Add the card, via the array to the component...here's your problem...
pane.add(deck[i - 1]);
In adding card to pane, it is first removed from pane, as it can only have one parent. What you need to do, is assign a unique instance of JButton to each element in the array
// You create an array of buttons
JButton[] deck = new JButton[9];
// Start your loop...
for(int i=0; i<9;i++)
{
// Assign the card reference to an element in the array...
deck[i]=new JButton();
// You set the icon
deck[i].setIcon(new ImageIcon("Back.jpg"));
// This is not a good idea...
deck[i].setSize(200,250);
// JButton is visible by default...
deck[i].setVisible(true);
// Add the card, via the array to the component...here's your problem...
pane.add(deck[i]);
Now, I can't see from your code snippet, but it would appear you are trying to use a null layout, this is highly inadvisable. Instead, make the time to learn and understand how to use appropriate layout managers.
If you're not using a null layout or don't know what I'm talking about, then things like setSize and setLocation won't work the way you expect them to...
Can you make a JFrame that just randomly chooses the provided three to four pictures as its background. So that when a user opens the JFrame, the JFrame will choose any of the stated pictures to choose from to be a background.
I want it something like this:
ImageIcon background = new ImageIcon("First Image.png");
JLabel label = new JLabel(background);
frame.add(label);
And the second picture:
ImageIcon background2 = new ImageIcon("Second Image.png");
JLabel label2 = new JLabel(background2);
frame.add(label2);
The third:
ImageIcon background3 = new ImageIcon("Third Image.png");
JLabel label3 = new JLabel(background3);
frame.add(label3);
And maybe the fourth:
ImageIcon background4 = new ImageIcon("Fourth Image.png");
JLabel label4 = new JLabel(background4);
frame.add(label4);
And I want some code so then the JFrame can use any one of these codes.
Also, is there a way to change the JFrame title randomly?
Like I want it something like:
'My Game: It's the best!'
...and then when the user opens the JFrame again, the title will change to, maybe:
'My Game: Try it, it's new!' and/or
'My Game: You can play it easily!' and/or
'My Game: Find all the mysteries...' and/or
'My Game: Money don't go on trees!' and other funny lines.
Hope I made it easy for you to understand!
Also consider Collections.shuffle(), illustrated here for List<JLabel> and here for List<Icon>.
You can use java.util.Random class to generate random numbers.
If you want to select random string/image/image path you can just declare an array and get a random item from it. Here's an example code for titles:
//class level variable, supply your own lines.
final String[] TITLES = new String[]{"My Game: It's the best!", "My Game: Try it, it's new!"}
//next snippet is random title generation
//it's better to use only one random instance,
//so you might want to declare this one on class level too
Random random = new Random();
int index = random.nextInt(TITLES.length); //get random index for given array.
String randomTitle = TITLES[index];
frame.setTitle(randomTitle);
You can do the same for image paths/images. Declare an array of type, get an object by random index:
final String[] IMAGE_PATHS = //initialization goes here
Random random = new Random();
String randomImagePath = IMAGE_PATHS[random.nextInt(IMAGE_PATHS.length)];
ImageIcon background = new ImageIcon(randomImagePath);
JLabel label = new JLabel(background);