just a quick question....
I am working in Java. I have 2 separate classes:
public class MulticastChatGUI extends javax.swing.JFrame{
}
and
public class MulticastThread extends Thread{
}
So, all I am really trying to do is to access an element from the GUI from within the Thread class, namely a Text Area. Is this possible? Thanks in advance for what is probably a very simple question.
Is it possible? Yes, but it must be done with care.
For instance you could give your MulticastThread class a MulticastChatGUI variable, and then pass in a reference of the current MulticastChatGUI instance into the MulticastThread object via a constructor parameter or a setter method.
e.g.,
// constructor
public MulticastThread(MulticastChatGUI multicastChatGui) {
this.multicastChatGui = multicastChatGui;
}
// or setter
public void setMulticastChatGUI(MulticastChatGUI multicastChatGui) {
this.multicastChatGui = multicastChatGui;
}
Up to now, the problem and solution is the same for any program where you want one class to talk to another.
Care must be taken however that whenever you call a Swing method on the JTextArea, you do so only on the Swing event thread, else you risk occurrence of a pernicious, hard to debug, and intermittent threading exception.
Note that it is cleaner not to have one object access the other object's fields directly (here the JTextArea), but instead have the class with the JTextArea make it private, and give it public methods that allow outside classes to change its shape in a controlled manner.
Related
Does anyone know if there's any way to intercept field accesses on the accessed class with Javassits?
public class Original{
public int field;
}
public class User {
Original o;
...
public int query(){
return o.field;
}
public void set(){
o.field=3;
}
}
What I want is that whenever another class accesses the field from any original instance, it runs some extra code (e.g. System.out.println("Reading field");)
I know that extending the class javassist.expr.ExprEditor and implementing the method void edit(FieldAccess fa), I can replace the field access for any other code that I want, but on the accessing class.
This requires to modify any class accessing that field. In our example the User class a replace all the read accesses by System.out.println(...);XXX=o.field, and all the write accesses by System.out.println(...);o.field=XXX
What I want to do is to convert a regular class instance into a proxy so any field access triggers a method execution. Is it feasible? Does it have any impact on possible subclasses?
Thanks in advance!
One way to do it is making all your proxy's fields private, and of course provide corresponding setters/getters, after that, you would implement a MethodHandler which will contain the method that you want to execute (ie. invoke) and you need to imeplement a MethodFilter in which you will designate which methods you want to intercept (in your case the getters/setters)
I think you're already familiar with javassist, so no code samples are needed i think, otherwise, i can edit this post to provide examples
I hope you get the idea ;)
I'm new to programming in Java and previously only programmed in Python. I have to write a class that doesn't include a constructor but instead has a method that "configures" the class object. So as I understand it, the class object is created as an object with no content and then its content is set by the configure method. An array is passed into the configure method, but when I try to set the class object equal to the array it says it's a type mismatch - I either need to change the class object to an array or the array to a class object, which from what I understand is undefined at that point. What is the class object? How can I make it an array without a constructor? I'm so confused and there seems to be little reference material for this situation online.
// UPDATE //
Here's the configure method per your requests.
I know you don't want English, but it's hard to explain just with a few lines of code - it's part of a larger program that finds the most efficient path across a map. There's a GUI Interface that operates through MapState that executes methods from BasicMapState and MapSolver that executes methods from BasicMapSolver. givenState is an array representing all the map tiles, with a 1 in the tile where the solver is currently located.
I would ideally like to store the givenState array and a parent move (what direction the solver chose to get to the givenState) as attributes of the MapState class object, but I'm lost. Please help.
public class BasicMapState implements MapState {
#Override
public void configureState(int[] givenState) {
MapState current = givenState
}
First of all, if you do not write a constructor, an empty constructor is autogenerated by the compiler. If you do not want the constructor to be called, make it privte like this
private BasicMapState() { }
If you do not want to make an object from this Class, you can work with static variables, otherwise you have to call the constructor from any public method.
To come to your problem:
As I understand you try to make the givenState Array equals the interface?
This makes no sense. If you want to set something like this, you have to declare a variable first which you can set. Interfaces are in most cases only for declaring method names. The interface is an inteerface and not Array.
To explain your error, that and array is not compatible with Object. If I remember correctly, Object is the basic root class from which ALL Classes and interfaces inherit.
I hope that helps a bit, if not let me know :)
John
mu~maybe
public class BasicMapState implements MapState {
private int[] givenState;
#Override
public void configureState(int[] givenState) {
this.givenState = givenState;
}
then maybe customize a compare method like
public boolean myCompare(BasicMapState bms){
return Arrays.equals(givenState, bms.getGivenState());
}
or just override the equals method
I am working on a simple calculator problem and i am making a class specifically to handle the operations. I am making two constructors within the class one taking one int and one taking two. What i plan to do is that when the user inputs the first number into the program, the first constructor will be called and the first number will be saved. When they enter the second number, the same instance of the class will be called but this time with both the variables in a constructor. Is this possible? Is there an easier way to do this? thanks.
You can't initialize the same instance of a class multiple times. What you can do, however, is change the value of any non-final instance or static variables in the class after you've called the constructor. It's best coding practice to avoid adding any code except for initialization of instance variables to the constructors, and what you can do is move any code in question to other methods so you can call it where you were thinking of calling the constructor the 2nd time.
No, this is not directly possible since a constructor can only be called upon class instantiation. You can use something like the builder pattern instead.
You can call another constructor within another overloaded constructor.
In your constructor, type this(yourParameters) and that calls the other constructor.
Example:
class Example
{
public Example()
{
this(1); // calls the other constructor
}
public Example(int par1)
{
// some code here
}
}
But other than that, you cannot call constructors explicitly like you can with methods.
So I've stumbled across several ways of implementing an ActionListener and I'm wondering if someone can walk me through the differences of how each works and whether there are reasons or advantages to use one over the other?
The first is below in a block of code:
public void actionPerformed(ActionEvent arg0) {
// CODE HERE
}
The second way I saw was within another block of code as:
private class myListener implements ActionListener {
// CODE HERE
}
The third was is simply having a separate class for the ActionListener, with similar code to that above, but within a separate class.
I'm wondering whether the method approach is more efficient as new objects don't have to be created for each, you simply reference this as the ActionListener rather than, for example, referencing new myListener(). Thank you.
There's no difference in speed in any of the options; you'll always have an object that implements the ActionListener interface. Avoiding an instance of a separate class will just save you a few bytes of memory.
Your choice really should be based on what makes sense for your code, structurally. For example, having your public class implement ActionListener may look weird for those who are using that class, especially if the ActionListener behavior is supposed to be private to the class and not used outside it.
So it's mostly a choice of what you think looks better in your code; the only real difference will be with regards to field / method access (e.g. a separate, non-inner class won't have access to private methods and fields of your class, an anonymous inner class can't access non-final variables of the enclosing method, etc).
I don't like or use "implements ActionListener".
I do like and use anonymous inner classes like:
btnPurplescreen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Color baseColor = Color.BLUE;
panelImage.setBackground(baseColor);
panelReference.setBackground(baseColor);
panelReference2.setBackground(baseColor);
baseType = BaseType.PURPLE;
}
});
You're stumbling in more ways that one.
In some sense, there is only one way to create a listener: there must be an object of a class that implements ActionListener, which means the class has the actionPerformed method.
There are three ways to do this:
You can modify a class you are already using for something else by marking it as implementing ActionListener and adding the actionPerformed method. This saves you creating a new class -- a savings of negligible value in most cases -- but mars otherwise perfectly good code. A few cases, when the existing
You can create a new named class. This is useful if you think the name is going to be meaningful to someone. If you are really using names like "MyListener", that's a clue that no, no-one cares about the name.
Finally, and usually, you can create an unnamed class. If all you want to do is add a fragment of code as a listener.
Whatever your choice, it's extremely unlikely to have any detectably effect on the time or memory performance of your finished system. The choice should be dictated by concerns about readability and maintainability.
I want to call a validation method inside a shared gwt class that i have created to store the validation logic (for user entered text fields)
suggestBox.addKeyUpHandler( new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
String boxText = suggestBox.getText();
if (new FieldVerifier().validUserName(boxText)) { //inner class used to instanciate the FieldVerifier class where validUserName(String ..) lives
now i could do this with a properly instanciated FieldVerifier class (rather than a inner class as above) - or indeed, perhaps make it abstract. but i have the suspicion i am missing something (ie. must be an elegant way of doing it).
looked on google code search, but didnt come across anything particularly helpful..
I'm not sure I got it, but try:
FieldVerifier.this.validUserName(boxText);
If you made the validUserName() method of FieldVerifier static then you could just call FieldVerifier.validUerName() directly, without having to instantiate a FieldVerifier object. If it's a fairly small class, though, the overhead of creating a new object is likely to be minimal.
i could do this with a properly instanciated FieldVerifier class (rather than a inner class as above)
Your use of FieldVerifier is not an inner class. It is indeed 'properly instanciated'. KeyUpHandler is an example of an anonymous inned class.
If I understand what you're trying to do, I would make validUserName() a static method. It doesn't appear to require or change any state; you just pass in something, run some verification logic on it, then return a boolean. This case is when you want to start looking at using statics.