I have a class SaveFile implementing ActionListener. The method in it takes a string argument compleName. How do I make completeName be accessable in actionPerformed method in that class.
Thanks
class SaveFile implements ActionListener {
public void uploadToDatabase(String completeName){
}
public void actionPerformed(ActionEvent e) {
// I want to access completeName here
}
}
}
just use it as a variable inside your class
class SaveFile implements ActionListener {
private string completeName;
public void uploadToDatabase(String compName){
//code...
this.completeName = compName;
}
public void actionPerformed(ActionEvent e) {
System.out.println(completeName);
}
}
}
Simply ensure you store completeName as an instance variable.
class SaveFile implements ActionListener {
private String completeName;
public void uploadToDatabase(String completeName){
// do other things
this.completeName = completeName;
}
public void actionPerformed(ActionEvent e) {
// use this.completeName to get that value
}
}
}
Related
Consider a method
public void doSomething(String actionID){
switch (actionID){
case "dance":
System.out.print("I'm dancing");
break;
case "sleep":
System.out.print("I'm sleeping");
break;
default:
System.out.print("I've no idea what I'm doing");
}
The implementation of the method depends on the value of the parameter. Is there a more elegant way to do this, or a different design pattern to replicate the behaviour?
If the caller decides what logic is executed by passing different strings, then why not just have them call different methods:
public void doSomething(String actionID) {...}
...
doSomething("dance");
doSomething("sleep");
VS.:
public void dance() {...}
public void sleep() {...}
...
dance();
sleep();
It seems like you're unnecessarily funnelling all the calls into doSomething
But the strings might not always be literals. What if you're taking them from the console?
You could provide static mappings from the strings to the corresponding functions:
class MyClass {
private static final Map<String, Consumer<MyClass>> map = new HashMap<>();
static {
map.put("sleep", MyClass::sleep);
map.put("dance", MyClass::dance);
}
public void doSomething(String actionID) {
map.getOrDefault(actionID, MyClass::doNothing).accept(this);
}
public void dance() {
System.out.print("I'm dancing");
}
public void sleep() {
System.out.print("I'm sleeping");
}
private void doNothing() {
System.out.println("I've no idea what I'm doing");
}
}
This makes scenarios where you have a lot of switch cases a lot cleaner.
Introduce an interface, e.g.
public interface HumanState {
public void tellMeWhatYouAreDoing();
}
encapsulate the logic in different implementations
public class DancingState implements HumanState {
#Override
public void tellMeWhatYouAreDoing() {
System.out.println("I'm dancing");
}
}
public class SleepingState implements HumanState {
#Override
public void tellMeWhatYouAreDoing() {
System.out.println("I'm sleeping");
}
}
public class UnknownState implements HumanState {
#Override
public void tellMeWhatYouAreDoing() {
System.out.println("I've no idea what I'm doing");
}
}
and use a map. E.g.
public class HumanStateExample {
public static void main(String[] args) {
HumanStateExample humanStateExample = new HumanStateExample();
humanStateExample.doSomething("dance");
humanStateExample.doSomething("sleep");
humanStateExample.doSomething("unknown");
}
private final HashMap<String, HumanState> humanStateMap;
public HumanStateExample(){
humanStateMap = new HashMap<String, HumanState>();
humanStateMap.put("dance", new DancingState());
humanStateMap.put("sleep", new SleepingState());
}
public void doSomething(String action) {
HumanState humanState = humanStateMap.get(action);
if(humanState == null){
humanState = new UnknownState();
}
humanState.tellMeWhatYouAreDoing();
}
}
I'm not sure how the pattern is called, but it is very useful if you need to delegate the method call based on more than one parameter:
Create a lot of handlers where each one knows when it is responsible for handling a call. Then just loop through them and invoke the first one matching the parameter.
edit: I renamed the class from FancyParameterActionFactory to FancyParameterActionUtility: it is not a factory, the name was misleading
//Your method, but this time with a complex object, not with a simple string.
public void doSomething(FancyParameterObject fpo){
FancyParameterActionUtility.invokeOn(fpo);
}
//The utility which can handle the complex object and decides what to do.
public class FancyParameterActionUtility{
public Interface FPAHandler{
void invoke(FancyParameterObject fpo);
boolean handles(FancyParameterObject fpo);
}
//Omitted: Different implementations of FPAHandler
public static List<FPAHandler> handlers = new LinkedList<>();
static{
handlers.add(new DanceHandler());
handlers.add(new SleepHandler());
//Omitted: Different implementations of FPAHandler
}
public static void invokeOn(FancyParameterObject fpo){
for(FPAHandler handler:handlers){
if (handler.handles(fpo)){
handler.invoke(fpo);
return;
}
}
//Default-Behavior
}
}
Here is a simple implementation of the command pattern based your sample problem. I define a general AbstractCommand abstract class which contains two methods. The first method, createCommand(), instantiates a command class based on an input string name. This is how you can delegate your string input to create the right type of command. The second method is doAction(), and this is left undefined, to be implemented later on by specific concrete command classes.
public abstract class AbstractCommand {
public static AbstractCommand createCommand(String name) {
try {
String clsName = name + "Command";
Class<?> cls = Class.forName(clsName);
AbstractCommand command = (AbstractCommand) cls.newInstance();
return command;
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
}
public abstract void doAction();
}
public class DanceCommand extends AbstractCommand {
public void doAction() {
System.out.println("I'm dancing");
}
}
public class TestCommandPattern {
public void doSomething(String actionID) {
AbstractCommand cmd = AbstractCommand.createCommand(actionID);
cmd.doAction();
}
public static void main(String[] args) {
TestCommandPattern test = new TestCommandPattern();
test.doSomething("Dance"); // should print "I'm dancing"
}
}
Now that this framework has been setup, you could easily add other commands for the various types of actions in your original problem. For example, you could create a SleepCommand class which would output I'm sleeping, or do whatever action you wish.
I need to pass a string from class to another class in Java (Bukkit), I have already read some similar questions, but I can't solve the problem.
I have a Main class
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new PlayerListener(this);
this.saveDefaultConfig();
String bannedBlocksString = this.getConfig().getString("bannedBlocks");
}
#Override
public void onDisable() {
}
}
And another class "PlayerListener"
public class PlayerListener implements Listener {
public PlayerListener(Main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
// public static final String bannedBlocksString = "DIAMOND_BLOCK; EMERALD_BLOCK";
public static final String[] bannedBlocks = bannedBlocksString.split("; ");
public static boolean isBannedBlock(String[] bannedBlocks, String blockPlaced) {
boolean returnValue = false;
for (String bannedBlock : bannedBlocks) {
if(blockPlaced.equalsIgnoreCase(bannedBlock)){
returnValue = true;
}
}
return returnValue;
}
#EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
String blockPlaced = event.getBlockPlaced().getType().toString();
if(!event.getPlayer().hasPermission("antibuild.block.noplace") && isBannedBlock(bannedBlocks, blockPlaced)) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You can not place this block.");
}
}
}
How can I get the value of bannedBlocksString in Main from the class "PlayerListener"?
Try this, I hope it works:
From Main:
PlayerListener pl = new PlayerListener(this);
this.saveDefaultConfig();
String [] bannedBlocksString = pl.getBannedBlocks();
From PlayerListener you have to declare get method:
public String [] getBannedBlocks(){
return this.bannedBlocks;
}
If you uncomment the bannedBlocksString in the PlayerListener then you can always access it in the Main class using PlayerListener.bannedBlocksString as the variable is static.
If you want to do it the other way arround and assign the value you need to remove the final from the variable and use the code beneath.
PlayerListener.bannedBlocks = bannedBlocksString.split("; ");
I have an abstract class Action with children like SendMessageAction.
I would like to run these actions in a service but how could I force implementation of each child ?
For example I would like to implement an abstract method : void run(Action action)
and methods "run" for each possible Action with an error if some methods are missing.
Any idea ?
Something like below should help you to get started. Happy coding!
Action.java
public abstract class Action {
protected abstract void runAction();
}
MessageSenderAction.java
public class MessageSenderAction extends Action {
public void runAction() {
//send message
}
}
SomeOtherAction.java
public class SomeOtherAction extends Action {
public void runAction() {
//do something else
}
}
ActionHandler.java
public class ActionHandler {
private final static ActionHandler INSTANCE = new ActionHandler();
private ActionHandler() {}
public static ActionHandler getInstance() {
return INSTANCE;
}
private List<Action> allActions = new ArrayList<Action>();
public void addAction(Action action) {
allActions.add(action);
}
public void runAllActions() {
for(Action action: allActions) {
//just to handle exception if there is any. Not to hamper other actions in case of any failures
try {
action.runAction();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
ActionDemo.java
public class ActionDemo {
public static void main(String... args) {
ActionHandler actionHandler = ActionHandler.getInstance();
Action msgSenderAction = new MessageSenderAction();
Action someOtherAction = new SomeOtherAction();
actionHandler.addAction(msgSenderAction);
actionHandler.addAction(someOtherAction);
actionHandler.runAllActions();
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im trying to get jTextField value in another class but always get error null exception. Here is my code :
Class Main :
public class FormTambahDoc extends javax.swing.JFrame {
Utility utility;
public FormTambahDoc() {
initComponents();
utility = new Utility();
setButton();
}
public String gettextIdentitasPengguna() {
return textIdentitasPengguna.getText();
}
private void setButton() {
btnSimpan.addActionListener(new ActionListener() {#Override
public void actionPerformed(ActionEvent e) { utility.cek();} });
}
}
Class another:
public class Utility {
FormTambahDoc formTambahDoc;
//FileJpaController controller;
public void cek()
{
String inputText = formTambahDoc.gettextIdentitasPengguna();
System.out.println(inputText);
//return `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
}
}
What's wrong in this code ?
You should create instance of FormTambahDoc before you ca use it:
FormTambahDoc formTambahDoc = new FormTambahDoc(); or get the instance from somewhere. Otherwise formTambahDoc will always be null. Check again your AWT tutorial.
Try following
public class FormTambahDoc extends javax.swing.JFrame {
Utility utility;
public FormTambahDoc() {
initComponents();
utility = new Utility(this);
setButton();
}
public String gettextIdentitasPengguna() {
return textIdentitasPengguna.getText();
}
private void setButton() {
btnSimpan.addActionListener(new ActionListener() {#Override
public void actionPerformed(ActionEvent e) { utility.cek();} });
}
}
public class Utility {
FormTambahDoc formTambahDoc;
//FileJpaController controller;
public Utility(FormTambahDoc aForm) {
formTambahDoc = aForm;
}
public void cek()
{
String inputText = formTambahDoc.gettextIdentitasPengguna();
System.out.println(inputText);
//return `Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException`
}
}
I have a question about inner class access. I am not experienced in Java, so please bear with me.
Below is the code i wrote:
public class MainFrame extends JFrame {
...
private String selectedNodeString = NULL; //outer class variable
private JPanel createControlPanel() {
...
parseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
tree.addTreeSelectionListener(new MyTreeSelectionListener());
}
});
class MyTreeSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
selectedNodeString = //compile error, can not resolve type
}
}
}
Below is an example from "thinking in java" explaining inner class access, where inner class can access outer class variable.
interface Selector {
...
}
public class Sequence {
private Object[] items;
private class SequenceSelector implements Selector {
...
private int i = 0;
public boolean end() { return i == items.length; }
public Object current() { return items[i]; }
public void next() { if(i < items.length) i++; }
}
}
So what is wrong with my code, is it more than 1 layer of inner class, and how to fix it?
Thanks
You are missing a curly brace after the method createControlpanel.
private JPanel createControlPanel() {
...
parseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
tree.addTreeSelectionListener(new MyTreeSelectionListener());
}
});
} // missing this one.