Change icon with click on button. Java - java

I use Netbeans to make a Java application. I am still a beginner. I have 4 buttons and I want to change an icon, when a user click one of them. I have already put buttons and one icon but I have no idea on how to continue.

You will need an ActionListener that changes the icon (use an ImageIcon for this). Add that ActionListener to the Button which should be responding to a click, with that action.
button.addActionListener(/*here your listener*/);

Are you using the windowbuilder of netbeans?
If yes, check the generated code for your specified button and see how they did it :)

Ok, i created a new JFrame Form to my package called TestFrame.
public class TestFrame extends javax.swing.JFrame {
static public ImageIcon imageCross;
static public ImageIcon imageCircle;
URL cross = TestFrame.class.getResource("cross.jpg");
URL circle = TestFrame.class.getResource("circle.jpg");
boolean clicked = true;
/**
* Creates new form TestFrame
*/
public TestFrame() {
imageCross = new javax.swing.ImageIcon(cross);
imageCircle = new javax.swing.ImageIcon(circle);
initComponents();
}
...
This is just how i declare my images.
Now i need to change them when i click on a button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(clicked) {
jButton1.setIcon(imageCircle);
clicked = false;
} else {
jButton1.setIcon(imageCross);
clicked = true;
}
}
Just add all your images you need. Add for every single JButton a actionPerformed() and switch your icons with a if-condition or maybe switch/case ( if you have more).

Related

Show picture when button is clicked

I am trying to get my action listener to show a picture when the button is clicked, but hide it until then. I also need it to only allow me to click it once. I have the button in a separate class that extends JButton so I'm unsure if that is affecting it. When I add the image using the action listener, it doesn't show the image whether I click it or not. When I add it to the button, it shows it before it is clicked(as expected). What is the best way to hide the image until the button is clicked? FYI, there are many instances of this button created, if that makes a difference.
This is the button class
import javax.swing.*;
public class EmptyButton extends JButton
{
public EmptyButton()
{
//add image to button
ImageIcon emptyImage = new ImageIcon("Empty.jpg");
JLabel empty = new JLabel(emptyImage);
}
}
This is the action listener
private class emptyButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
game.noTreasureFound();
treasuresFoundTextField.setText(String.valueOf(game.getTreasuresFound()));
treasuresLeftTextField.setText(String.valueOf(20-game.getTreasuresFound()));
triesLeftTextField.setText(String.valueOf(game.getTriesLeft()));
}
}
use JLabel#setVisible(true) to make image visible on click. Initially call setVisible(false) to hide it
use JButton#setEnabled(false) to disable button after click

Making custom close and minimize button

I have a decorated JFrame. I need to make close button and minimize button. What should I do?
Here is my code snippet:
public Startup()
{
setTitle("STARTUP");
setSize(800,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);
setLocationRelativeTo(null);
setVisible(true);
}
Your approach is very unique and will look quite good. There are many ways to solve your problem. Now, as per your request, you want a CLOSE and a MINIMIZE button. Let us make the following Actions.
private final Action exitAction = new AbstractAction("Exit")
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
};
private final Action minimizeAction = new AbstractAction("Minimize")
{
#Override
public void actionPerformed(ActionEvent e)
{
setState(JFrame.ICONIFIED);
}
};
Now, let us apply the above actions to JButtons:
JButton closeButton = new JButton(exitAction);
JButton miniButton = new JButton(minimizeAction);
There you have it. Now, all you need to do is add your buttons to your JFrame.
Note For Eclipse Users
this code will come in your minimize button when You click On minimize button in Eclipse.
YourFrameName is the Frame name you had set or it is set by default, use that frame name here:
YourFrameName.setState(YourFrameName.ICONIFIED);

Handle RadioButton events after button clicked

help,
my questions are:
why isn't itemStateChanges triggered, I tried to put it in the inner class ButtonHandler and also in RadioButtonHandler Im having trouble with it, what is the right way to do it?
I want to trigger and check the marked JRadioButtons after the user click the "check" button.
What is the right way to check which button was clicked, I feel like comparing the strings is bad programming practise. Maybe using an ID ?
How should I make a "reset" button(start over), I want to uncheck all radio buttons and run the constructor once again.
Thank you for your help !
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ExamFrame extends JFrame {
static ArrayList<Question> qArrList;
JRadioButton a1,a2,a3,a4;
public ExamFrame() {
super("Quiz");
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
Exam exam = new Exam();
qArrList = exam.getExam();
int count=0;
for(Question q : qArrList){
count++;
JLabel questionLabel = new JLabel(count+". "+q.getQustion()); //swing constant ?
ArrayList<String> ansRand = q.getAllRandomAns();
a1 = new JRadioButton(ansRand.get(0));
a2 = new JRadioButton(ansRand.get(1));
a3 = new JRadioButton(ansRand.get(2));
a4 = new JRadioButton(ansRand.get(3));
add(questionLabel);
add(a1);add(a2,gbc);add(a3);add(a4);
ButtonGroup radioGroup = new ButtonGroup(); //logical relationship
radioGroup.add(a1);radioGroup.add(a2);radioGroup.add(a3);radioGroup.add(a4);
}
//buttons:
JButton checkMe = new JButton("Check Exam");
JButton refresh = new JButton("Start Over");
ButtonHandler handler = new ButtonHandler();
checkMe.addActionListener(handler);
refresh.addActionListener(handler);
add(checkMe);
add(refresh);
}
/** Listens to the radio buttons. */
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Start Over")){ //id?
//how to do this?
}
else{
RadioButtonHandler handler = new RadioButtonHandler();
a1.addItemListener(handler);
System.out.println("success?");
}
JOptionPane.showMessageDialog(ExamFrame.this, String.format("You pressed: %s", e.getActionCommand()));
}
public void itemStateChanged(ItemEvent e) //can i add it here?
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("yes?"));
System.out.println("success!");
}
}
public class RadioButtonHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("radio state changed"));
}
}
}
why "itemStateChanges" isn't triggered, i tried to put it in the inner
class "ButtonHandler" and also in "RadioButtonHandler" Im having
troubles with it, what is the right way to do it? I want to trigger
and check the marked JRadioButtons after the user click the "check"
button.
ButtonHandler is implemented with ActionListener only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent) function belongs to ItemListener. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener. However, one more thing to note, that JButton doesn't respond to ItemListener but JRadioButton will. Because this Item events are fired by components that implement the ItemSelectable interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like
comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource(), check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String) function and check the name you were expecting. Of-course you should assign the name using setName(String) after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all
radio buttons and run the constructor once again.
Well you are working with ButtonGroup. And ButtonGroup has a nice function: clearSelection() to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener implemented class, Yes i can see that But:
i can not see that you have actually registered an instance of that class(a1.addItemListener(handler);) to any component before performing any action on the component to which ButtonHandler is registered to: checkMe, refresh
In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with JButton.setActionCommand(String) function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial:
How to Write an ItemListener
How to Write an ActionListener
How to Use the ButtonGroup Component

How to use KeyPressed in Java

I am working on my Java assignment. I have to create a virtual keyboard and my professor didn't teach us about KeyPressed and I am stuck for couple of days now.
My question is if I want the user to type something in the JTextFiled and want to change the background of the JButton to appear in different color whenever the user type any of the characters that are available on the keyboard, how can I do that?
For example, if the user hit the spacebar, I want the color of the spacebar on the frame to appear black and when the user releases the button, the color changes to it's original background color.
I know how to create JFrame, JButton, JLabel, and JPanel.
This is a simple code that I have created.
import javax.swing.*;
import java.awt.*;
public class Assignment extends JFrame {
private JButton jbtnSpace = new JButton(" ");
private JPanel jpnl1 = new JPanel();
private JTextArea txta = new JTextArea(10,62);
public Assignment(){
jpnl1.add(txta);
jpnl1.add(jbtnSpace);
this.add(jpnl1);
}
public static void main(String[] args) {
Assignment jfrm = new Assignment();
jfrm.setTitle("Assignment");
jfrm.setSize(710,440);
jfrm.setVisible(true);
jfrm.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Please help. Thank you
Try this:
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
int i=evt.getKeyChar();
if(i==KeyEvent.VK_SPACE) //or any Key Constant
{
//your code of changing the color
}
}
I hope this helps. You must understand the working though, as described in one of the comments.

Unselecting RadioButtons in Java Swing

When displaying a group of JRadioButtons, initially none of them is selected (unless you programmatically enforce that). I would like to be able to put buttons back into that state even after the user already selected one, i.e., none of the buttons should be selected.
However, using the usual suspects doesn't deliver the required effect: calling 'setSelected(false)' on each button doesn't work. Interestingly, it does work when the buttons are not put into a ButtonGroup - unfortunately, the latter is required for JRadioButtons to be mutually exclusive.
Also, using the setSelected(ButtonModel, boolean) - method of javax.swing.ButtonGroup doesn't do what I want.
I've put together a small program to demonstrate the effect: two radio buttons and a JButton. Clicking the JButton should unselect the radio buttons so that the window looks exactly as it does when it first pops up.
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
/**
* This class creates two radio buttons and a JButton. Initially, none
* of the radio buttons is selected. Clicking on the JButton should
* always return the radio buttons into that initial state, i.e.,
* should disable both radio buttons.
*/
public class RadioTest implements ActionListener {
/* create two radio buttons and a group */
private JRadioButton button1 = new JRadioButton("button1");
private JRadioButton button2 = new JRadioButton("button2");
private ButtonGroup group = new ButtonGroup();
/* clicking this button should unselect both button1 and button2 */
private JButton unselectRadio = new JButton("Unselect radio buttons.");
/* In the constructor, set up the group and event listening */
public RadioTest() {
/* put the radio buttons in a group so they become mutually
* exclusive -- without this, unselecting actually works! */
group.add(button1);
group.add(button2);
/* listen to clicks on 'unselectRadio' button */
unselectRadio.addActionListener(this);
}
/* called when 'unselectRadio' is clicked */
public void actionPerformed(ActionEvent e) {
/* variant1: disable both buttons directly.
* ...doesn't work */
button1.setSelected(false);
button2.setSelected(false);
/* variant2: disable the selection via the button group.
* ...doesn't work either */
group.setSelected(group.getSelection(), false);
}
/* Test: create a JFrame which displays the two radio buttons and
* the unselect-button */
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RadioTest test = new RadioTest();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3,1));
contentPane.add(test.button1);
contentPane.add(test.button2);
contentPane.add(test.unselectRadio);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Any ideas anyone? Thanks!
You can do buttonGroup.clearSelection().
But this method is available only since Java 6.
The Javadoc of the class ButtonGroup itself gives some hint about how this can be achieved:
From the API doc of class ButtonGroup:
Initially, all buttons in the group are unselected. Once any button is selected, one button is always selected in the group.There is no way to turn a button programmatically to "off", in order to clear the button group. To give the appearance of "none selected", add an invisible radio button to the group and then programmatically select that button to turn off all the displayed radio buttons.
Try adding a third invisible button to the button group. When you want to "deselect", select the invisible one.
Or you can use Darryl's Select Button Group which doesn't require you to use an "invisible button".
You can use a click counter:
private ButtonGroup radioGroup = new javax.swing.ButtonGroup();
private JRadioButton jRadioBtn1 = new javax.swing.JRadioButton();
private int clickCount = 0;
private void jRadioBtn1Clicked(java.awt.event.MouseEvent evt) {
// Remove selection on a second click
if (jRadioBtn1.isSelected()) {
if (++clickCount % 2 == 0) {
radioGroup.clearSelection();
}
}
}
You can use setselected(false) method to unselect the previous selected button.
I don't know if this will help but have you tried to use doClick() method?
jRadioButtonYourObject.doClick();
Input - NONE
Return- void
I had a similar problem and tried everything in this thread to no avail. So I took a look at all the methods of JRadioButton and found that method from JRadioButton's parent class.
In my program, I had two radio button independent of each other and it was programed so that only one was selected.
After the user enters data and hits a button the program clears all text fields and areas and deselects the radio button. The doClick() did the job of deselecting the radio button for me; the method "performs a "click"."
I know yours is different and you probably would have to program the doClick() method for every radio button that is selected.
http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html
search for doClick()
When you want to deselect, select invisible. For that you add a third invisible button to the button group.
In my case I use Jgoodies project to bind GUI components to Java model.
The RadioButton component is bound to a field
class Model {
private SomeJavaEnum field; // + getter, setter
}
In such case ButtonGroup.clearSelection doesn't work since the old value still retains in the model. Straightforward solution was to simply setField(null).
Use this helper class SelectButtonGroup.java
direct link to the class source
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SelectUnselected extends JPanel {
private static String birdString = "Bird";
private static String catString = "Cat";
private static Integer selectedIndex = -1;
private static AbstractButton hiddenButton = new JRadioButton(catString);
private final static AbstractButton birdButton = new JRadioButton(birdString);
private final static AbstractButton catButton = new JRadioButton(catString);
//Group the radio buttons.
private SelectButtonGroup group = new SelectButtonGroup();
public SelectUnselected() {
super(new BorderLayout());
//Create the radio buttons.
hiddenButton.setVisible(false);
hiddenButton.setSelected(true);
group.add(birdButton);
group.add(catButton);
group.add(hiddenButton);
ActionListener sendListener = e -> {
checkSelectedRadioButten();
};
birdButton.addActionListener(sendListener);
catButton.addActionListener(sendListener);
hiddenButton.addActionListener(sendListener);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(birdButton);
radioPanel.add(catButton);
add(radioPanel, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void checkSelectedRadioButten(){
System.out.println("selectedIndex = " + selectedIndex + "\ngroup.getSelectedButton() = " + group.getSelectedIndex());
if(group.getSelectedIndex() == selectedIndex){
hiddenButton.setSelected(true);
selectedIndex = -1;
System.out.println("getText = " + group.getSelectedButton().getText());
}else{
selectedIndex = group.getSelectedIndex();
System.out.println("getText = " + group.getSelectedButton().getText());
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("RadioButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new SelectUnselected();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
}
You can use your own ButtonGroup (1), or use modified instance (2), like this:
ONLY SINCE JAVA 6:
(1) public class NoneSelectedButtonGroup extends ButtonGroup {
#Override
public void setSelected(ButtonModel model, boolean selected) {
if (selected) {
super.setSelected(model, selected);
} else {
clearSelection();
}
}
}
(2) ButtonGroup chGroup = new ButtonGroup() {
#Override
public void setSelected(ButtonModel m, boolean b) {
if (!b) clearSelection();
else
super.setSelected(m, b);
}
};
take from https://blog.frankel.ch/unselect-all-toggle-buttons-of-a-group/

Categories

Resources