how can i set JButton that changes the JLabel location on the JPanel when it pressed?
how to implement the actionlistener for this on the JButton?
You want to add the action listener to the button first
button.addActionListener(new ButtonListener());
Next you want to create the custom class
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
label.setLocation(xValue, yValue);
}
}
}
Change the xValue/yValue to the x and y values that you want the label to change to.
I hope this helps!
Related
So for my program i have three buttons;
Button1: 8
Button2: 5
Button3: 3
public void actionPerformed(ActionEvent e) {
JButton b1= (JButton) e.getSource();
JButton b2= (JButton) e.getSource();
String button= b1.getText();
String button2 = b2.getText();
System.out.println("b1: " + button);
System.out.println("b2: " + button2);
I'm trying to check which buttons are pressed and storing them into the variable. So when the user presses 8, button should be 8, and once they press any second button, button2 should get that button
Do i make a new ActionEvent?
Currently both your buttons refer to the same source (I.e the same button)
If the actions to be triggered are similar in nature (for example, the buttons in MineSweeper, they are different buttons, but the actions to be triggered are the same), then you don't have to create multiple action listeners for multiple buttons. You can let your buttons add the same action listener:
//Example
class MyPanel extends JPanel{
private JButton btn1, btn2;
public MyPanel(){
btn1 = new JButton("Button 1");
btn2 = new JButton("Button 2");
ButtonHandler bn = new ButtonHandler();
btn1.addActionListener(bh);
btn2.addActionListener(bh);
}
}
Infact, what you wanted to do is just a one-liner:
private class ButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
System.out.println((JButton)e.getSource().getText());
}
}
However, if you have different actions for different buttons (for example, Start Game and Exit Game), then you can create separate action listeners for them.
So maybe you want to check the source of the event? Like:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
System.out.println("b1 pressed");
} else if (e.getSource() == b2) {
System.out.println("b2 pressed");
} else {
System.out.println("some other button pressed");
}
}
and you should really create different buttons outside of the scope of this actionPerformed method!
EDIT
The example solution by user3437460 is much better than this oneā¦
Every component can hold information on it, by putClientProperty();
This mechanism is kind of map, so can hold few named objects. We use only one.
This obcjet (pie of information) is not visible for user, it is not text written on button like getText() in few tries, is only for consuming by algorithm. There can live not only primitives or strings, but live objects too.
class MyPanel extends JPanel{
private JButton btn1, btn2;
public MyPanel(){
btn1 = new JButton("Button 1");
btn1.putClientProperty("myinternalsense", 8); // <-- here
btn2 = new JButton("Button 2");
btn1.putClientProperty("myinternalsense", 5); // <-- here
btn1.putClientProperty("myfunctor", new MyFunctor() ); // <-- here
ButtonHandler bn = new ButtonHandler();
btn1.addActionListener(bh);
btn2.addActionListener(bh);
}
}
This information is accessible in any context, for example common event handler to many buttons.
private class ButtonHandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
System.out.println((JButton)e.getSource().getClientPropertygetText("myinternasense")); // <-- here
}
}
Ok so I have 2 jPanels.
one of them has a number of buttons that when pressed should add text to the the textfield that is in the second jPanel.
I am brand spanking new to swing with previously only having to write back end code and web based code so I am having difficulty seeing how you would accomplish this.
I only have buttons created in one panel and a textfield in another so i suspect code would be irrelevant.
Any articles that someone could point me to or examples are greatly appreciated.
So I had this problem ones,
So Lets say you have two JFrame JFrame1 and JFrame2
In order to communicate with each other at runtime both has to have most recent initialized object of each individual frame.
Now lets say this is your first frame where is your textbox,
public class JFrame1 extends JFrame{
JTextField jTextField= null;
public JFrame1() throws HeadlessException {
super("JFrame");
setSize(200, 200);
jTextField = new JTextField();
add(jTextField);
setVisible(true);
}
public void setValueToText(String value){
jTextField.setText(value);
}
}
Then This is second and where is your Button,
public class JFrame2 extends JFrame{
JButton jButton= null;
JFrame1 frame1=null;
public JFrame2() throws HeadlessException {
super("JFrame");
frame1=new JFrame1();
jButton = new JButton("Clieck Me");
add(jButton);
setVisible(true);
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame1.setValueToText("Hi");
}
});
setVisible(true);
}
public static void main(String[] args) {
JFrame2 jf= new JFrame2();
jf.setSize(200, 200);
}
}
Now Just run second class file and click one button which will set hi on your textbox which is in second frame.
So As you see answer lay's in Initialized second object in frame.
My execution is like,
Run JFrame2
Initialized JFrame1 in JFame2 const.
you can make the JTextField an instance variable of the enclosing JFrame and make the two panels inner classes of it. By this, the two panels will have a reference to the same field which belongs to the outer class.
So, you will end up having something similar to:
public class Outer extends JFrame{
private JTextField text = new JTextField();
...
public Outer(){
this.add(new Inner1(), BorderLayout.NORTH);
this.add(new Inner2(), BorderLayout.SOUTH);
}
class Inner1 extends JPanel{
...
public Inner1(){
this.add(text);
}
}
class Inner2 extends JPanel implements ActionListener{
private JButton button = new JButton();
public Inner2(){
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == button)
text.setText("Hello StackOverFlow");
}
}
}
add your code to change the text in another panel, when a button clicked in the first panel.
mybutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//do your logic to change the text in another panel
}
});
I want to remove JButton when user click JButton.
I know that I should use remove method, but it did not work.
How can I do this?
Here is my code:
class Game implements ActionListener {
JFrame gameFrame;
JButton tmpButton;
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4;
public void actionPerformed(ActionEvent e) {
gameFrame.remove(tmpLabel1);
gameFrame.getContentPane().validate();
return;
}
Game(String title) {
gameFrame = new JFrame(title);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setBounds(100, 100, 300, 500);
gameFrame.setResizable(false);
gameFrame.getContentPane().setLayout(null);
tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg"));
tmpLabel4.setSize(200, 200);
tmpLabel4.setLocation(50, 100);
tmpButton = new JButton("Play");
tmpButton.setSize(100, 50);
tmpButton.setLocation(100, 350);
tmpButton.addActionListener(this);
gameFrame.getContentPane().add(tmpLabel4);
gameFrame.getContentPane().add(tmpButton);
gameFrame.setVisible(true);
}
}
If hiding the button instead of removing works for your code then you can use:
public void actionPerformed(ActionEvent event){
tmpButton.setVisible(false);
}
for the button.But the button is just hidden not removed.
The simplest solution might be to...
Attach an ActionListener to the button, see How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details
When the ActionListener is clicked, extract the source of the event, JButton buttonThatWasClicked = (JButton)actionEvent.getSource()
Remove it from it's parent...
For example...
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();
As some ideas...
First of all in your actionPerformed method you need to check that the button is clicked or not. And if the button is clicked, remove it. Here's how :
if(e.getSource() == tmpButton){
gameFrame.getContentPane().remove(tmpButton);
}
add this to your actionPerformed Method
don't add your button to jframe but add each component you want!
public void actionPerformed(ActionEvent event)
{
//gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
gameFrame.getContentPane().validate();
}
or hide your button like this
public void actionPerformed(ActionEvent event)
{
tmpButton.setVisible(false);
}
I have a slight issue with my Actionlistener, when i click button nothing happens ?? I do not see where the problem is, so another pair of eyes could help me out :)
public class GameOptions extends JPanel implements ActionListener{
public GameOptions(){
System.out.println("GameOptions Class test blabla");
easyButton().addActionListener(this);
mediumButton().addActionListener(this);
hardButton().addActionListener(this);
JPanel center = new JPanel(new GridLayout(4,1,10,10));
center.add(new JLabel("Chose Difficulty Level"));
center.add(easyButton());
center.add(mediumButton());
center.add(hardButton());
this.add(center, BorderLayout.CENTER);
this.setPreferredSize(this.getPreferredSize());
this.setFocusable(true);
this.requestFocusInWindow();
}
private JButton easyButton(){
JButton levelEasy = new JButton("Easy");
return levelEasy;
}
private JButton mediumButton(){
JButton levelMedium = new JButton("Medium");
return levelMedium;
}
private JButton hardButton(){
JButton levelHard = new JButton("Hard");
return levelHard;
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if(src == easyButton()){
System.out.println("Easy");
}
else if(src == mediumButton()){
System.out.println("Medium");
}
else if(src == hardButton()){
System.out.println("Hard");
}
else{
}
}
}
Your xxxButton() methods create new JButtons each time, and so you add the ActionListener to a newly created JButton and then discard the button, and then add a completely different JButton, one without the ActionListener to the GUI.
Suggestion: create your JButtons, set a variable to them, add your ActionListener, and add the same button to the GUI.
So instead of this:
easyButton().addActionListener(this); // creates one JButton
center.add(easyButton()); // creates a completey different JButton
do this:
JButton easyButton = easyButton();
easyButton.addActionListener(this);
center.add(easyButton);
Note, if this were my code, I'm not sure that I'd use JButtons at all. Instead perhaps I'd use either JRadioButtons or a JComboBox.
You're creating each JButton with a function. And later you try to add it like center.add(easyButton()); but the one you added a ActionListener isn't the same button as this one. You're creating each one with new, so the reference isn't the same.
You should do it like this:
JButton buttonEasy = easyButton();
buttonEasy.addActionListener(this);
center.add(buttonEasy);
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);