Obtain object from overriden method - java

public class Job_GUI extends javax.swing.JFrame {
private JobDTO jdto;
public Job_GUI() {
initComponents();
}
private void menuEditJobActionPerformed(java.awt.event.ActionEvent evt) {
editJob.setVisible(true);
//here I want to obtain the updated dto.
}
}
public class JobDTO extends BaseDTO {
//setters and getters
}
class ListDataUI {
private void initListeners() {
summaryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
summaryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final int selectedRowIndex = summaryTable.getSelectedRow();
if (selectedRowIndex != -1) {
BaseDTO dto = data.get(summaryTable.convertRowIndexToModel(selectedRowIndex));
} else {
}
}
}
});
}
}
I am not sure how to obtain the BaseDTO object dto to menuEditJobActionPerformed method so I can display all the values of the object. How do I pass this from valueChanged when event occurs? I'm simply using a table, when a row is selected, the dto state changes, need to pass this new state to the class Job_GUI actionperformed method

Declare dto right after your class GUI { declaration.
That way it will have global scope so all your functions can see it.
class GUI {
BaseDTO dto;
private void menuEditJobActionPerformed(java.awt.event.ActionEvent evt) {
editJob.setVisible(true);
//Now you can access "dto"
}
}
class ListDataUI {
private void initListeners() {
summaryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
summaryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final int selectedRowIndex = summaryTable.getSelectedRow();
if (selectedRowIndex != -1) {
/*BaseDTO */dto = data.get(summaryTable.convertRowIndexToModel(selectedRowIndex));
//not declaring a new object
} else {
}
}
}
});
}
}

Related

How to use Assert.assertTrue in anonymous inner class?

Im want to test a propertyChangeSupport. For that, I wrote this Test:
private boolean changeRecognized = false;
#Test
public void testAddMapObject(){
Bot testBot = new Bot(UUID.randomUUID(), "test", new GeoPoint(0d, 0d));
PropertyChangeListener listener = new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == "mapObjekt")
changeRecognized = true;
}
};
testListe.addPropertyChangeListener(listener);
testListe.addMapObjekt(testBot);
Assert.assertTrue(changeRecognized );
}
Is there a way to move the Assert.assertTrue into the PropertyChangeListener? I tried it, but the test passed every Time, even when I didn't call testListe.addMapObject(testBot)
I would suggest creating a named class for this:
class SomeTest ...
static class SpyListener implements PropertyChangeListener {
private boolean changeRecognized = false;
#Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName() == "mapObjekt") {
changeRecognized = true;
}
}
public void assertRecognized() {
Assert.assertTrue(changeRecognized);
}
}
#Test
public void testAddMapObject() {
Bot testBot = new Bot(UUID.randomUUID(), "test", new GeoPoint(0d, 0d));
SpyListener listener = new SpyListener();
testListe.addPropertyChangeListener(listener);
testListe.addMapObjekt(testBot);
listener.assertRecognized();
}
...

How to initiate a change event for a TreeModel in Java?

Suppose you got a JTree with a model that implements TreeModel, and all nodes implement TreeNode.
Suppose then that something happens in the background with the model (not through the GUI) like a CRUD-event, that update the model and should update the JTree.
Since the model is CRUD-affected from other views it does not seems like a good idea to use the DefaultTreeModel for this task, correct me if I'm wrong.
I guess you need to signal the change to the TreeModel in somehow, like fire some event in some way?
Btw I have not managed to implement the methods:
public void addTreeModelListener( TreeModelListener l )
public void removeTreeModelListener( TreeModelListener l )
I guess these methods need to be implemented for such a feature.
I like to use this kind of generic ListenerList:
public class ListenerList {
private final List<Object> list = new ArrayList<Object>();
public ListenerList() {
}
public void addListener(Object listener) {
list.add(listener);
}
public void removeListener(Object listener) {
list.remove(listener);
}
public <T> T getNotifier(Class<T> intf) {
ClassLoader cl = intf.getClassLoader();
return intf.cast(Proxy.newProxyInstance(cl, new Class[] {intf},
(Object proxy, Method method, Object[] args)
-> actualInvoke(method, args)));
}
private Object actualInvoke(Method method, Object args[]) {
Object result = null;
for (Object listener: list) {
try {
result = method.invoke(listener, args);
} catch (IllegalAccessException e) {
LOG.error("Error invoking listener method", e);
} catch (InvocationTargetException e) {
LOG.error("Error invoking listener method", e);
}
}
return result;
}
}
That I use in my model class:
public class MyTreeModel implements TreeModel {
private final ListenerList listeners = new ListenerList();
private final TreeModelListener notifier = listeners.getNotifier(TreeModelListener.class);
public void addTreeModelListener( TreeModelListener l ) {
listeners.addListener(l);
}
public void removeTreeModelListener( TreeModelListener l ) {
listeners.removeListener(l);
}
protected void fireTreeNodesChanged(TreeModelEvent e) {
notifier.treeNodesChanged(e);
}
protected void fireTreeNodesInserted(TreeModelEvent e) {
notifier.treeNodesInserted(e);
}
protected void fireTreeNodesRemoved(TreeModelEvent e) {
notifier.treeNodesRemoved(e);
}
protected void fireTreeStructureChanged(TreeModelEvent e)
notifier.treeStructureChanged(e);
}
...
}

How to write a asynchronous file handler in Vertx

I am new to Vertx.
I am playing with the API and I am trying to write a FileSizeHandler. I don't know if it is the correct way to do it but I would like to have your opinions.
In my code I would like to use the handler like this :
public class MyVerticle extends AbstractVerticle {
#Override
public void start() throws Exception {
getFileSize("./my_file.txt", event -> {
if(event.succeeded()){
Long result = event.result();
System.out.println("FileSize is " + result);
} else {
System.out.println(event.cause().getLocalizedMessage());
}
});
}
private void getFileSize(String filepath, Handler<AsyncResult<Long>> resultHandler){
resultHandler.handle(new FileSizeHandler(filepath));
}
}
Here is my FileSizeHandler class :
public class FileSizeHandler implements AsyncResult<Long> {
private boolean isSuccess;
private Throwable cause;
private Long result;
public FileSizeHandler(String filePath){
cause = null;
isSuccess = false;
result = 0L;
try {
result = Files.size(Paths.get(filePath));
isSuccess = !isSuccess;
} catch (IOException e) {
cause = e;
}
}
#Override
public Long result() {
return result;
}
#Override
public Throwable cause() {
return cause;
}
#Override
public boolean succeeded() {
return isSuccess;
}
#Override
public boolean failed() {
return !isSuccess;
}
}
What bothers me in the handler, is that I have to do it in the constructor of the class. Is there a better way to do it?
First of all, you called your class FileHandler, but it's not. It's a result.
You declare handler in Vert.x like that:
public class MyHandler implements Handler<AsyncResult<Long>> {
#Override
public void handle(AsyncResult<Long> event) {
// Do some async code here
}
}
Now, for what you do, there's vertx.fileSystem():
public class MyVerticle extends AbstractVerticle {
#Override
public void start() throws Exception {
vertx.fileSystem().readFile("./my_file.txt", (f) -> {
if (f.succeeded()) {
System.out.println(f.result().length());
}
else {
f.cause().printStackTrace();
}
});
}
}

What to do about "unchecked call to generic class?"

I have this class:
package Main;
public abstract class Click123<T extends java.awt.Component> ////////////////
{
boolean debugging = false;
public abstract void singleClick(java.awt.event.MouseEvent e); ////////////////
public abstract void doubleClick(java.awt.event.MouseEvent e); ////////////////
public abstract void tripleClick(java.awt.event.MouseEvent e); ////////////////
public abstract void manyClick(java.awt.event.MouseEvent e); ////////////////
public abstract int getFreq();// how long thread sleeps; i.e., click interval
public Click123(T target) ////////////////
{
target.addMouseListener ////////////////
(
new java.awt.event.MouseAdapter() ////////////////
{
Thread cp = null;
public void mouseClicked(final java.awt.event.MouseEvent e)
{
if (cp != null && cp.isAlive())
cp.interrupt();
if (e.getClickCount() == 1)
{
cp = new Thread(new ClickProcessor(new java.util.concurrent.Callable<Void>() {
#Override public Void call() throws Exception {
singleClick(e); //////////////////////////////////////////
return null;
}
}));
cp.start();
}
else if (e.getClickCount() == 2)
{
cp = new Thread(new ClickProcessor(new java.util.concurrent.Callable<Void>() {
#Override public Void call() throws Exception {
doubleClick(e); //////////////////////////////////////////
return null;
}
}));
cp.start();
}
else if (e.getClickCount() == 3)
{
cp = new Thread(new ClickProcessor(new java.util.concurrent.Callable<Void>()
{
#Override public Void call() throws Exception {
tripleClick(e); //////////////////////////////////////////
return null;
}
})
);
cp.start();
}
else manyClick(e); //////////////////////////////////////////
} // mouseClicked
} // new MouseAdapter
); // add mouseListener
} // Click123
class ClickProcessor implements Runnable
{
java.util.concurrent.Callable<Void> eventProcessor;
ClickProcessor(java.util.concurrent.Callable<Void> eventProcessor)
{
this.eventProcessor = eventProcessor;
}
#Override public void run()
{
try
{
System.out.println("About to sleep " + getFreq());
Thread.sleep(getFreq()); // this value comes from implementation
eventProcessor.call();
} catch (InterruptedException e) { System.out.println(e);}
catch (Exception e) { System.out.println(e);}
} // run
} // class ClickProcessor
} // class Click123
The only warning I get from Netbeans is about the "package visible inner class" ClickProcessor.
I compiled my project using this command line:
javac -Xlint:unchecked -classpath main\*.java gbl\*.java
It gave warnings about "unchecked call to Click123<T> as a member of raw type Click123" in several places, including the reference to it in this class:
public class GridCell extends JTextField {
int row,
col;
char content;
Color foreground,
background;
GridCell(){
content = ' ';
foreground = Color.BLACK;
background = Color.WHITE;
disableKeyCombo(KeyEvent.VK_A, KeyEvent.VK_C, KeyEvent.VK_V, KeyEvent.VK_X,
KeyEvent.VK_H);
new Click123(this) ////////// flagged warning unchecked call to Click123
{
#Override
public void singleClick(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e))
{
if( ! Game.getAvailable().contains("*"))
Game.changeSMBorder(e.getComponent().getX(),
e.getComponent().getY());
else
Game.changeSbBackground(e.getComponent().getX(),
e.getComponent().getY());
}
Game.btnClearBorders.setEnabled(true);
}
#Override public void doubleClick(MouseEvent e){
if(SwingUtilities.isRightMouseButton(e))
{
if(btnUndo.isEnabled())
btnUndo.doClick();
}
}
#Override
public void tripleClick(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e))
{
if(btnRedo.isEnabled())
btnRedo.doClick();
}
}
#Override
public void manyClick(MouseEvent e) {
}
#Override
public int getFreq() {
return CLICK_FREQUENCY;
}
};
}
... class goes on much further
}
What, if anything, can/should I do?
Try changing
new Click123(this)
to
new Click123<GridCell>(this)
Click123 is a generic class which means it has a type parameter, written between angular brackets. For Click123 the type parameter T must be a subclass of Component, which GridCell is.
Using a raw type like List or Set should be avoided. A raw type is a generic type that is used without type parameters. When generics were introduced, raw types were only allowed for compatibility with code written before generics.
However, looking at your class it looks like there is no reason why Click123 should be generic at all. Couldn't the constructor just take a Component rather than a T?
It looks like you're not fully using the Generics try:
new Click123<GridCell>(this)
How to fix unchecked call warning in Java?

Applying key bindings to state transitions when implementing a state pattern

here's a programming style question about the best strategy to map input keys to actions in a class that implement the state pattern.
I'm dealing with two classes:
The first implements the state pattern, which controls a multi-state physical device:
class DeviceController {
State _a, _b, _current;
// Actions that may prompt a transition from one state to another
public void actionA() { ... }
public void actionB() { ... }
public void actionC() { ... }
public State getStateA() { ... }
public State getStateB() { ... }
public void setCurrentState() { ... }
};
The second is a KeyListener that retrieves all keyboard input and calls the appropriate action from the device controller when a pressed input key matches a (for the time being) hard-coded bindings table:
class KeyDemo implements KeyListener {
DeviceController _controller;
...
#Override
public void keyPressed(KeyEvent arg0) {
char key = Character.toUpperCase(arg0.getKeyChar());
switch (key) {
case 'A':
_controller.actionA();
break;
case 'B' :
...
}
...
}
Is there a best-practice coding style to bind the keys to the actions in the controller ? Do I have to go through a switch statement, as in the sample code ? It seems to me that this solution is somewhat dirty code: isn't the state pattern supposed to eliminate unmaintanable if and switch control structures ?
Thank you for your suggenstions.
Using polymorphism you can achive your goal. I've used enum but maybe it would be more appropriated to use interfaces or an abstract class and then implement each of the key processors. What do you think?
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
enum KeyProcessor {
A {
void executeAction() {
_controller.actionA();
}
},
B {
void executeAction() {
_controller.actionB();
}
};
private static final DeviceController _controller = new DeviceController();
void executeAction() {
System.out.println("no action defined");
}
}
class DeviceController {
State _a;
State _b;
State _current;
// Actions that may prompt a transition from one state to another
public void actionA() {
System.out.println("action A performed.");
}
public void actionB() {
System.out.println("action B performed.");
}
public void actionC() {
}
public State getStateA() {
return null;
}
public State getStateB() {
return null;
}
public void setCurrentState() {
}
} // end class DeviceController
public class KeyDemo implements KeyListener {
DeviceController _controller;
// ...
#Override
public void keyPressed(KeyEvent arg0) {
keyPressed(Character.toUpperCase(arg0.getKeyChar()));
// ...
}
public void keyPressed(char c) {
KeyProcessor processor = KeyProcessor.valueOf(c + "");
if (processor != null) {
processor.executeAction();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
public static final void main(String[] args) {
KeyDemo main = new KeyDemo();
main.keyPressed('A');
main.keyPressed('B');
}
} // end class KeyDemo
class State {
}

Categories

Resources