Is there a method to get the button associated with a particular command string?
For instance if I define a button with:
button.setActionCommand("unique_toggle");
Having that string "unique_toggle", is it possible to retrieve that button from another class? I am beginner at Java, excuse if this question may seem obvious to you.
Yes, you can access to your button and its associated button's command. If you need to a button's command, that possibly means that you should consider redesining your programm because this approach is not advisable and very dirty way to do what you want to achieve.
When it comes to answer to your question,
Lets say Foo1 is your GUI class.
class Foo1{
JButton button;
public Foo1(Foo2 otherClass)
{
button = new JButton();
otherClass.setButtonAddress(button);
}
..... other methods
}
Foo2 is the class, in where you want to access button's command text.
class Foo2{
JButton buttonFromOtherClass;
//This is the method, in where you need command string of the button
private void getCommandsString()
{
Foo1 foo1 = new Foo1(this);
//After the initialization of Foo1, you can get every information of the button
String actionCommand = buttonFromOtherClass.getActionCommand();
}
public void setButtonAddress(JButton button)
{
buttonFromOtherClass = button;
}
}
Related
To begin with I'm in this just a few days so I am sorry if this is a silly question, I did my search but I didn't find what I was looking for.
Simply said, I've got a class like this:
public class logout extends JButton {
private static final long serialVersionUID = -4813329911065574369L;
public static JButton logout = new JButton("Izloguj se");
public logout()
{
//parameters like font, foreground etc
}
And when I try to call it in another class, like this:
ctrl.add(prikaz.logout.logout);
I get an old plain button with text I defined in class but none of the parameters I defined for it.
I know I can add the button with its settings if I do something like:
JPanel lgtBtn = new logout();
But I would like to do it directly with add.
You define the logout button with:
public static JButton logout = new JButton("Izloguj se");
This creates a new JButton with the specified text. But then the class you are in also extends JButton, and it is set up in the constructor. So you have two JButtons, but you only ever reference the one that is not set up. I would just get rid of the line of code above, and reference the button as prikaz.logout (not prikaz.logout.logout).
I feel that I'm missing something when it comes to statically typed languages. When I pretty much only used perl way back, there were many ways I could tell an object which function to call.
Now that I'm in Java, I fail to see how I can do something similar in an easy fasion
I have a generic Button class. This is subclassed by all of the actual buttons that will be used: Each with a different method to call when clicked.
Is there really no way of passing a reference to a method to call when clicked, so that I can use one class for all of the buttons?
At present, I create buttons like this:
// Specifically using the subclass that sets "firemode" to "close"
FiremodeClose fc = new FiremodeClose(Settings.ui_panel_start, Settings.ui_panel_row_firemode, game);
painter.addSelectionButton(fc);
clickTracker.addSelectionButton(fc);
This ofcourse couses a myriad of subclasses, each one differing only in placement, label/graphics, and method call. It makes more sense to do something similar to this:
// Generic button, the method that sets "firemode" is somehow passed as arguement to the contsructor.
Button fc = new Button(&referenceToFunctionToCallWhenClicked, otherArguementsEtc);
painter.addSelectionButton(fc);
clickTracker.addSelectionButton(fc);
Like I said, I feel I must be missing something, because it makes sense that there should be a way of achieving this, thus letting me getting away with just one Button class without any subclasses.
If that's what interfaces are for, then I must've been using them for something else than their intended purpose. I'd love to see an answer involving some code examples for this.
Have your Buttons implement the observer pattern, just like Swing does. Then you can even just use Swing's ActionListener interface, or even Runnable is not a bad choice, or e.g. roll your own:
// Your interface.
public interface MyButtonListener {
public void buttonClicked ();
}
// Somewhere else:
Button fc = ...;
fc.addButtonListener(new MyButtonListener () {
#Override public void buttonClicked () {
// do stuff here
}
});
// And in your Button have it simply iterate through all of its registered
// MyButtonListeners and call their buttonClicked() methods.
There are myriads of other ways to implement this. For example, you could even do something like:
public interface ThingThatCaresAboutButtons {
public void buttonClicked (Button button);
}
Then have your higher level UI logic be something like:
public class MyUI implements ThingThatCaresAboutButtons {
#Override public void buttonClicked (Button button) {
if (button == theOneButton) {
// do whatever
} else if (button == theOtherButton) {
// do whatever
}
}
}
And when creating buttons:
theOneButton = new Button(theUI, ...);
theOtherButton = new Button(theUI, ...);
Or have them maintain a list instead of a single object passed in the constructor. Or whatever.
Endless ways to skin this cat but hopefully you get some inspiration here. Check out how Swing works.
You could for instance use Runnable:
class MyButton {
private final Runnable action;
public MyButton(Runnable action) {
this.action = action;
}
...
}
And then call action.run() when the button is clicked.
Then when creating a button, you can pass a reference to a method, as long as it has the void return type, and takes no arguments.
Button fc = new Button(EnclosingClass::methodToCall, otherArguementsEtc);
Other interfaces can be used for different method signatures.
In Java 8 you can use both method references and lambdas:
class Button {
Button(Runnable function) {
}
}
Button b1 = new Button(() -> System.out.println("works!"));
Button b2 = new Button(System::gc);
You can do similar thing in Java <8, but it's more verbose with anonymous classes:
Button b3 = new Button(new Runnable() {
#Override
public void run() {
System.out.println("works!");
}
});
I have a quick question. I don't get it...
I've got a JFrame where I add a JComboBox:
JComboBox<String> Team_ComboBox = new JComboBox<>();
Team_ComboBox_Handler ComboBox_Listener = new Team_ComboBox_Handler();
Team_ComboBox.addActionListener(ComboBox_Listener);
Team_ComboBox.addItem("Test 1");
Team_ComboBox.addItem("Test 2");
On this Frame I have a button which opens another JFrame.
Play = new JButton();
Play.setText("Play");
Play.setPreferredSize(dimension);
Play.addActionListener(menuhandler);
private class main_menuhandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Play){
teams Team = new teams();
Team.teams();
disposeMainMenue();
}
if(e.getSource()==Close) {
System.exit(DO_NOTHING_ON_CLOSE);
}
}
}
Anyway, I would like to transfer the Selected value of the Combobox to a method of the other class. I know how I can get the itemvalue of the combobox in the method itself (with getselecteditem) But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method.... I created another ActionListener (comboBox_Listener) but I haven't put any code into it...
Any idea? Thanks a lot in advance
Several issues appear to me:
Your main question:
But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method
Your likely best solution is to change your code and variable declaration placement so that you can access the JComboBox fromt he actionPerformed method. If you're declaring the combobox from within a method or constructor, change this so that it is a proper instance field of the class.
Other problems:
You should not be creating multiple JFrames. If you need a dependent window, then one should be a JDialog. If not, then consider swapping views with a CardLayout.
Learn and follow Java naming conventnions so others can better understand your code. Class names begin with capital letters and methods and variable names don't for instance.
I am not sure why you're doing this: System.exit(DO_NOTHING_ON_CLOSE);. Why pass that constant into the exit method?
Use a constructor for your action listener class:
private class main_menuhandler implements ActionListener {
private JComboBox<String> Team_ComboBox;
public main_menuhandler(JComboBox<String> Team_ComboBox){
this.Team_ComboBox = Team_ComboBox;
}
}
Now you can create the class main_menuhandlervia the constructor and add the combobox to it.
In your Overriden action you have access to it.
Try playing around with this as your code snippet isn't broad enough to actually provide proper code. But this should answer your question
I am making a program where clicking a custom JButton allows you to make your next click paint an image at the point on the screen. Members of this JButton class have certain data that is unique to each separate button. My question is if I can pass the JButton object when clicked on through a method into a class which would then extract the data. I was thinking something like this:
Click Method in JButton{
OutsideClass.setObject(this); //problem
}
OutsideClass{
Object obj = new Object();
public void setObject(Object Obj){
obj = Obj;
}
Click Method in OutsideClass{
place obj;
obj.getData;//Methods within JButton that retrieve specific data
}
My issue is the "setObject" part of the JButton. It doesn't recognize "this" as the specific Object clicked and thus doesn't work. Is there another way to get the desired effect? Thanks!
I am trying to use this String called "username" from another method, but I can't seem to figure out what to do.
I have this bit of code right here, which assigns a text field's entry to a variable, but I can't seem to use this variable in another method
//Configuring content pane
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(129, 36, 120, 20);
UsernameFrame.getContentPane().add(formattedTextField);
UsernameFrame.setVisible(true);
//Assigning text field entry to variable
String username = formattedTextField.getText();
Now, I am trying to use this variable in the method pasted below, but I don't know what I am missing..
public void actionPerformed(ActionEvent e){
if(username.length() < 5){
}
//Execute when the button is pressed
System.out.println("The button has been pressed");
}
This is probably something really simple I am missing, thanks for your help guys.
(full code)
http://pastebin.com/RMszazd4
Declare username right after your class declaration like this:
public class App {
private String username;
public static void main(String[] args) {
...
}
...
}
If these are two separate methods you will need to reassign the username variable again or you can create a global variable outside of your methods.
You might want to pass in the string variable "username"as a parameter to another method since it would not recognize the scope of your string in another method unless its declared global.
You don't appear to have a way of reading the JFormattedTextField. If I understand what you're trying to do correctly, you could declare formattedTextField as an instance variable, and then declare username inside the listener:
public class Frame {
JFrame UsernameFrame = new JFrame("Welcome");
private JFormattedTextField formattedTextField;
....
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = formattedTextField.getText();
if (username.length() < 5) {
}
// Execute when the button is pressed
System.out.println("The button has been pressed");
}
});
Now you have a reference to the text of the JFormattedTextField to do what you will with each time the button is pressed.