Issue with button icons, Java 8-Queens puzzle - java

The problem I am running into is this: I have a grid of buttons in a JPanel, these buttons are supposed to change to an image of a queen when I click them. The code looks like this:
private Component createButtonBlack() {
final JButton button = new BoardButton();
final ImageIcon queen = new ImageIcon("/images/queen.png");
button.setBackground(Color.BLACK);
button.setPreferredSize(new Dimension(40, 40));
class QueenClick implements ActionListener {
public void actionPerformed(ActionEvent event) {
button.setIcon(queen);
button.repaint();
}
} // end QueenClick
ActionListener queenClicker = new QueenClick();
button.addActionListener(queenClicker);
return button;
} // end createButtonBlack
The problem (image not appearing) occurs on both the methods for creating black and white buttons but the methods are the same except for the color. Ideally I would like to be able to un-click the buttons and the image disappears but I do not know how to do that.
I am having difficulty with other parts of my 8queens GUI based problem so if you have any suggestions let me know!
Also if you need more code I will certainly supply it. Thank you.

State the exact problem when asking a question.
These buttons are supposed to change to an image of a queen when I click them.
So I'm guessing the icon doesn't change?
Did you:
Verify the ActionListener code is executed?
Verify the Icon was read properly?
You can easily add a System.out.println(...) to verify both of the above.
final ImageIcon queen = new ImageIcon("/images/queen.png");
I'm guessing the problem is the leading "/" in the path. The "/" tells the file system to look at the root of the drive.
if you have any suggestions let me know!
There is no need to create two methods. You can just do:
Component button = createButton();
button.setBackground( Color.BLACK );
There is no need to create individual ActionListeners. You can create a single generic listener with code like:
ActionListener queenClicker = new ActionListener()
{
#Override
public void actionPerformed(Action Event e)
{
JButton button = (JButton)e.getSource();
button.setIcon( queen );
//button.repaint(); // not needed the setIcon method will do the repaint()
}
}

Related

Changing to color of a JToggleButton only when the button is selected, afterwards it will go back to the default color

This may end up being noted as a formerly asked question, however the other questions have yet to answer the question that I have asked properly, to what I need them to do.
I want it to be that whenever I click the ToggleButton it will set the color of the ToggleButton to black (in this case), and then when I unclick the button it will return to the default color.
Here is the code for the individual button, its possible Ill have to create a new class (I am using Eclipse) but if anyone could help id be extremely thankful. (I also have Jigloo)
jToggleButton4 = new JToggleButton();
getContentPane().add(jToggleButton4);
FlowLayout jToggleButton4Layout = new FlowLayout();
jToggleButton4.setLayout(jToggleButton4Layout);
jToggleButton4.setText("Black");
jToggleButton4.setPreferredSize(new java.awt.Dimension(133, 249));
You can take the default color/ the color you keep initially and can toggle the background color with an ActionEvent,
JToggleButton jtb = new JToggleButton("My Button");
Color defaultColor=jtb.getBackground();
jtb.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ev) {
if(jtb.getBackground()==defaultColor)
jtb.setBackground(Color.BLACK);
else
jtb.setBackground(defaultColor);
repaint();//repaint your frame
System.out.println("BackGround color changed!");
}
});

How coud I create these kind of Button using Java Swing?

I want to create button without any borders or shadow, but an icon instead using java swing component. How can I accomplish this?
Real Button
JButton btnNewButton = new JButton("");
btnNewButton.setContentAreaFilled(false);
btnNewButton.setBorderPainted(false);
btnNewButton.setBorder(null);
btnNewButton.setIcon(new ImageIcon(path));
This will give you a real button without any borders around the given image to work with. Note that in this state the button doesn't have a "click animation" anymore. For such an animation you could use the .setSelectedIcon(selectedIcon);
Clickable Image
ImageIcon img = new ImageIcon(path);
JLabel button = new JLabel(img);
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//Set pressed or something else
}
});
But this one just provide you a clickable Image and should only be used when a clickable Image without any other intentions is needed.
Note that this way is just a workaround.

image does not open when button is pressed in actionListener in my GUI?

I am trying to get an image to open when the PlaySci button is pressed so I put the image in the PlaySci action listener, however it only opens when the exit button is pressed?
I have looked at it for hours and still dont understand why, I have tried to get rid of the exit button alltogether but then the image does not show at all.
I made the image into a JLabel at the top:
ImageIcon scis1 = new ImageIcon("scis.jpg");
private JLabel picture = new JLabel(scis1);
Here is the code for my PlaySci button ActonListener:
class PlaySciHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String computerRand = sps.computerChoice();
txtComputerRand.setText(computerRand);
String result = sps.play(Sps.SCISSORS);
txtResult.setText(result);
picture.setBounds(60, 200, 400, 400);// this is the image I want displayed when the PlaySci button is pressed
panel.add(picture);
}
}
This is the exit button ActionListener (That for some reason is the only way to display the image):
class exitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame, //when this button is pressed the image comes up?
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
This is the code creating the button and adding the ActionListener:
btnPlaySci = new JButton ("Scissors!");
btnPlaySci.setBounds(180, 40, 110, 20);
btnPlaySci.addActionListener(new PlaySciHandler());
panel.add (btnPlaySci);
btnPlaySci.setForeground(Color.MAGENTA);
Any help would be appreciated.
You should repaint your panel after you add picture to it. See the code for PlaySciHandler actionPerformed method.
class PlaySciHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String computerRand = sps.computerChoice();
txtComputerRand.setText(computerRand);
String result = sps.play(Sps.SCISSORS);
txtResult.setText(result);
picture.setBounds(60, 200, 400, 400);// this is the image I want displayed when the PlaySci button is pressed
panel.add(picture);
panel.repaint();//Must repaint the panel .
}
}
Note: As a side note I would suggest you to never use null Layout for JPanel.Use the inbuilt Layouts provided by Swing. You can get more information about Layouts usage at this official site. Another one is that always stick with java naming conventions. Class exitHandler should be written as ExitHandler instead.To know more have a look at this official site.
Don't add the JLabel in the class PlaySciHandler implements ActionListener block.Add it in your createForm() method and make it invisible: picture.setVisible(false);
and when you want to display after a button click, make it visible : picture.setVisible(true);

ActionEvent for jButton given a jRadioButton option

So basically, I'm trying to make a simple program here with GUI that let's you make a choice given two jRadioButtons as choices of which either of the two leads to a corresponding storyline in similar fashion to visual novels. The problem however is that I'm having trouble connecting the idea of a jButton to a choice from a jRadioButton.
The concept is like this: In a frame, there's a jTextArea which displays strings of texts forming a storyline which gives two options to choose from here and there as represented by two jRadioButtons which then must be executed by a jButton.
So far, the only logic I've placed inside the ActionListener for both jRadioButtons is having to disable the other once a jRadioButton is clicked while the jButton is intentionally blank. Anyone got any similar program or module he / she would like to share, at least, the logic on this one programatically speaking?
We usually use RadioButtons to choose between one of a few options and only one button can be selected at a time. To get this functionality, you need to add your buttons to a javax.swing.ButtonGroup . Here is a quick example:
//Fields declared in your main GUI class
JRadioButton option1,option2;
JButton goButton; //executes the "Story"
//Constructor code or place in init() method that constructor calls:
{
//initialize buttons and place them in your frame.
ButtonGroup buttonGroup = new javax.swing.ButtonGroup();
buttonGroup.add(option1);
buttonGroup.add(option2);
buttonGroup1.setSelected(option1.getModel(), true);
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goButtonActionPerformed(evt);
}
});
}
private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(option1.isSelected()) {
//place text in your text area
}
if(option2.isSelected()) {
//place different text in your text area
}
}

Java swing: Models and Button color changes

I'm super confused with what exactly models are supposed to do in java swing. At present I'm basically trying to create a model for JButton to detect if it isPressed(); My essential goal of the model is to do something like this:
if(myButton.isPressed() ) {
myButton.setBackground(Color.RED);
}
else{//when any other button is pressed?
myButton.setBackground(Color.WHITE);
}
At present my code is something like this:
numberButton = new JButton("Num");
numberButton.setBounds(20,40,80,30);
numberButton.addChangeListener(new ChangeListener() {
public void stateChanged (ChangeEvent e){
if (model.isPressed() ){
doColorChange(model);
}
}
});
I understand that this is totally wrong, but I have no idea where, and I haven't found a tutorial that really explains what I'm doing wrong or why I need a model for this at all.
Please help me restore my sanity! Thanks a lot!
Use radio buttons in a button group.
import java.awt.image.BufferedImage;
import java.awt.*;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;
class RedAndWhite {
public static Image getColoredImage(Color color, int size) {
BufferedImage bi = new BufferedImage(
size,
size,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(color);
g.fillRect(0,0,size,size);
g.dispose();
return bi;
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Image red = getColoredImage(Color.RED, 32);
Image white = getColoredImage(Color.WHITE, 32);
JPanel p = new JPanel(new GridLayout(1,0,5,5));
ButtonGroup bg = new ButtonGroup();
for (int ii=0; ii<6; ii++) {
JRadioButton b = new JRadioButton();
b.setSelectedIcon(new ImageIcon(red));
b.setIcon(new ImageIcon(white));
b.setContentAreaFilled(true);
bg.add(b);
p.add(b);
}
JOptionPane.showMessageDialog(null, p);
}
});
}
}
I think what you want is register an ActionListener or Action with the button in order to handle button presses, right?
Edit: rereading your answer, it seems you want to highlight the button that is being pressed, right? In that case, try to use your own button ui (subclass the one of the look and feel you're using). BasicButtonUI has a method protected void paintButtonPressed(Graphics g, AbstractButton b) that you could override to apply the highlight when the button is being pressed.
there are follows ways how to make JButton nicer
1) most nicest way is painting only Borders from ButtonModel on Mouse events
2) override whole BasicButtonUI with all rellevant Look and Feels
3) put there Icons and override all possible methods implemented in JButton API
4) best at all would be implement Custom Look and Feel
5) create Custom JComponent based on JLabel/JComponent
I always took it that the ButtonModel is intended (mostly) for use by the UI class to render the button in its pressed/not-pressed/armed/selected/... state and track changes to that state.
If you simply want to paint the button red (that is waht you want?) while it is pressed your solution seems fine to me.
If you have a Toggle Button (that remains pressed after it has been clicked to indicate a "selected" state, you might want to use an ItemListener and check for
ItemEvent.ITEM_STATE_CHANGED == ItemEvent.SELECTED // paint red
ItemEvent.ITEM_STATE_CHANGED == ItemEvent.DESELECTED // paint white
If you want to execute application logic when the button is clicked, use an ActionListener.

Categories