Is there a way to get the propery value we declared this way?
JButton button = new javax.swing.JButton(){
public int value=0;
}
button.addActionListener(listener);
//in action listener
public void ActionPerformed(ActionEvent evt){
JButton btn = (JButton)evt.getSource();
btn.value =2; //error
}
You cannot access properties / methods of annonymous class outside of the instance itself.
The reason is that the compiler knows that btn is a JButton, not your extension, and you can't cast to this extension, as it doesn't have a name.
You need to create an internal class or class in a separate file and instantiate it, for example:
static class MyButton extends JButton {
public int value=0;
}
// ....
MyButton btn = new MyButton();
btn.addActionListener(listener);
// ....
#Override public void actionPerformed(ActionEvent evt){
MyButton btn = (MyButton)evt.getSource();
btn.value = 2;
}
What you can do is use Component.setName() to save at least a string with your Component.
Related
I'm writing a pretty big class and don't want to post it here. The question is the following, how do I refer to the button that was pressed in the constructor of a different class? Let's say, I want to disable it after some actions in the listener. If the listener were anonymus or were an inner class of the SomeClass, I would just use the name of the variable like this:
button.setEnabled(false);
But how can I do it when my listener is a separate class? Tried using e.getModifiers().setEnabled(false) and e.getSource().setEnabled(false), didn't work.
public class SomeClass extends JPanel {
private JButton button = new JButton("Button");
public SomeClass() {
button.setActionCommand("button");
button.addActionListener(new ButtonListener());
}
public static void main(String[] args) {
// TODO code application logic here
}
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String src = e.getActionCommand();
if (src.equals("button")) {
//some actions here
//then
}
}
}
Try this ((JButton)e.getSource()).setEnabled(false)
It must work)
e.getSource() return component to which this event refers( docs)
Hey all I can change the text of 1 single button easily with "final" but I need to create lots of buttons for a flight booking system, and when the buttons are more, final doesnt work ...
JButton btnBookFlight;
eco = new EconomyClass();
eco.setSeats(5);
for(int i=0;i<20;i++){
btnBookFlight = new JButton("Book" +i);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnBookFlight.setBackground(Color.RED);
btnBookFlight.setOpaque(true);
btnBookFlight.setText("Clicked");
}
});
btnBookFlight.setBounds(77, 351, 100, 23);
contentPane.add(btnBookFlight);
}
I would be glad if you can suggest me any trick to get over this.I want to change a buttons color or text when it is clicked or maybe some other cool effects when mouse over but for now only text or color will be enough =).Thanks for your time!
Use the source of the ActionEvent in the ActionListener
btnBookFlight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton)event.getSource();
button.setBackground(Color.RED);
...
}
});
btnBookFlight has to be final for the inner class (ActionListener) to access it.
From JLS 8.1.3
Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.
If this is not permitted, then the JButton may be accessed using the source component of the ActionEvent itself using getSource.
However, that said, the simplest solution would be to move the JButton declaration within the scope of the for loop and make it final:
for (int i = 0; i < 20; i++) {
final JButton btnBookFlight = new JButton("Book" + i);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnBookFlight.setBackground(Color.RED);
...
}
});
}
Just avoid using anonymous classes for your action listener and the final constraint will disappear.
What I mean is use:
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton src = (JButton)e.getSource();
// do what you want
}
}
So, I have a JTextArea. I have added keyboard action to it's input/action maps.
On enter press, JDialog is supposed to be created, along with it's contents. And I need to add keyListener to a button it will contain, which i can't, because that button doesn't ahve final modifier. If I set it to final, I can't edit it's properties.
Here's a snippet of the code:
class blabla extends JTextArea
{
getInputMap.put(KeyStroke.getKeyStroke("ENTER"), "pressedEnter");
getActionMap.put("pressedEnter", new AbstractAction()
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
JDialog dialog;
JButton confirm;;
//JDialog
dialog = new JDialog(Main.masterWindow, "newTitle", true);
dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
dialog.addWindowListener(new WindowAdapter()
{
public void windowActivated(WindowEvent e)
{
//this doen't work, it asks me to declare confirm as final
//and I have to request focuse here due to Java bug
confirm.requestFocus();
}
});
//JButton for confirming
confirm = new JButton(lang.getString("ok"));
confirm.setAlignmentX(Component.CENTER_ALIGNMENT);
confirm.addKeyListener(new KeyAdapter()
{
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
//this doen't work, it asks me to declare confirm as final
confirm.doClick();
}
}
});
dialog.add(confirm);
dialog.pack();
dialog.setLocationRelativeTo(Main.masterWindow);
dialog.setVisible(true);
}
How can I make this work?
Option 1: make confirm a class field.
Option 2: You could create a dummy final JButton variable, final JButton finalConfirm = confirm; and pass in the confirm reference, and then work on this variable inside of the inner class.
Option 3: don't use an anonymous inner class for your Key Binding's AbstractAction, but rather a private inner class with a constructor that takes the JButton instance.
I've got my buttons working right, and I'm a listener to each button like this:
for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getSource());
}
};
I need some way to find the button in the array.
try this
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
In order to get label, try this.
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
String label = button.getLabel(); //Deprecated
String label2 = button.getText();
}
};
ActionEvent has a method getActionCommand() that will get a JButton's actionCommand String. This is usually it's text as well (for JButtons).
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
l1.setText("");//name of level what you want
t1.setText(null);//text field what you want
t2.setText(null);//text field what you want
}
I am trying to make a GUI in Java, using something along these lines:
public class GUIApp
{
DrawingPanel dp;
buttonPanel bp;
ova = Oval;
public GUIApp()
{
JFrame win = new JFrame("Drawing App");
dp = new DrawingPanel();
bp = new buttonPanel(this);
//Settings for panels and frame
ova = new Oval(100,100,100,100);
}
public void setOval(int c){
//Change color of oval
}
}
Then in my buttonPanel class I have this:
public class ButtonPanel extends JPanel
{
private JButton btnRed, btnGreen, btnBlue;
public ButtonPanel(GUIApp d)
{
ButtonListener listener = new ButtonListener();
btnRed = new JButton("Red");
btnGreen = new JButton("Green");
btnBlue = new JButton("Blue");
btnRed.addActionListener(listener);
btnGreen.addActionListener(listener);
btnBlue.addActionListener(listener);
setBackground(Color.lightGray);
GridLayout grid = new GridLayout(3,1);
add(btnRed,grid);
add(btnGreen,grid);
add(btnBlue,grid);
}
private class ButtonListener implements ActionListener{
public void clickButton(ActionEvent event) {
Object location = event.getSource();
if (location == btnRed){
d.setOval(1);
}
else if(location == btnGreen){
d.setOval(2);
}
else if(location == btnBlue){
d.setOval(3);
}
}
}
}
But netbeans gives an error for the inner ButtonListener class, and I don't know why. I also don't know how to correctly call the setOval from within that class to the GUIApp class. What am I doing wrong?
The problem is that when you implement ActionListener you must define the method actionPerformed(ActionEvent e); you haven't done that in your ButtonListener class. You can't name the method anything that you want (as you've done with clickButton), so you should just rename your clickButton method to actionPerformed (and go ahead and add an #Override annotation too).
Now in order to call d.setOval from within your inner class, d must be in scope when the actionPerformed method is called. There are a couple ways to achieve this: you could make d a member variable of your class, or you could define your ButtonListener as an anonymous class.
For example, if you saved d as a member variable then your code would look like this:
public class ButtonPanel {
private GUIApp d;
public ButtonPanel(GUIApp d) {
this.d = d;
// The rest of your code here...
}
}
Or, you could use an anonymous class like this:
public ButtonPanel(GUIApp d) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
Object location = event.getSource();
if (btnRed.equals(location)) {
d.setOval(1);
} else if (btnGreen.equals(location)) {
d.setOval(2);
} else if (btnBlue.equals(location)) {
d.setOval(3);
}
}
};
// The rest of your constructor code here ...
}
Note: Notice how I also changed the use of == to equals() for object equality.