Java Swing GUI Console Component - java

I'm currently creating my first java swing application and as part of the GUI I have a small console in the form of a JTextField component. I would like to be able to print to this console from anywhere in the application using a command like console.print(String). I believe that I should be using print stream but I can't figure out how to make this work properly from anywhere (i.e. in another class which doesn't reference the console) .
I would also like to maintain the ability to print out to the eclipse console. Any help on this matter would be much appreciated.

Create a class for the purpose of accepting and distributing console strings; give it a static method to print to your console. Give that class a (static) reference to your console component.
something like:
public MyConsole
{
private static TextField field;
public static void setField(TextField givenField)
{
field = givenField;
}
public static void print(String msg)
{
field.append(msg);
}
}
The other parts of your application can import MyConsole and call MyConsole.print(msg);

Related

how to print "hello world" without MAIN method and also without using STATIC and FINAL key word in java

class a {
public static void main(String args[]) {
}
}
i want to print "hello world" without touch or use above code and also without use of static and final keyword......
What are the different ways to initiate code execution.
Use public static void main(String args[]) { ... }
Use your static class initializer static { ... }. Problem: You need to get the class to load first. Solution: attempt to start the main method, but that means you need to have at least an empty main. However - OP states we cannot use 'static'.
Use an instance initializer { ... }. Problem: How do you instantiate an instance. Solution: initialize a static field with a class instance. However - OP states we cannot use static fields.
So what is left. I assume that we can use the empty main posted by the OP. From there on we build up a 4th solution:
public enum Play {
PLAY;
{ System.out.println("Hello World!"); }
public static void main(String args[]) { }
}
This should fulfill the conditions:
we do not modify the static main method, although we need the empty body just to get the class loaded.
we do not use a static initializer, we use an instance initializer instead.
to instantiate, and get the instance initializer started, we use an enum. Enum's start the initializer for each instance, meaning for each of the enum constants.
Also note the output when you try to execute a class without a main:
$ java -classpath . Play
Error: Main method not found in class Play, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
So that leaves us also the clue that we potentially can use javafx.application.Application. I did not investigate this trail any further.
You can create a JavaFX application, which is usually for displaying a GUI, and use it to output hello, world to the console and immediately shut the JavaFX GUI system down. JavaFX applications are executed by a special launch path in the java launcher. JavaFX applications do not need a main, static and final keywords.
The following snippet is just for demo purposes, I wouldn't recommend writing a JavaFX application unless you actually wish to display a GUI.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
public class PlayApp extends Application {
#Override
public void start(Stage stage) {
System.out.println("hello, world");
Platform.exit();
}
}
// Totally useless code from the original question
// goes below the real app code and is just ignored
// and never used when the application runs.
class a {
public static void main(String args[]) {
}
}
You need to use Oracle Java 8+ to compile and execute the JavaFX application as below:
javac PlayApp.java
java PlayApp
The a class is in the PlayApp.java file only to meet the original poster's requirement from a comment:
it means the above code is fixed, you can't modify the above code but yes u can write anything to print "hello world" above or belove this code
Really, if you are writing a console application, just use a standard app format (with a static main method) instead:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Unrelated advice on asking questions
In future, if you post such questions, I suggest that you also supply the reason for the question and why the bizarre constraints are placed on solutions. Also, address concerns such as WorldEnder's first comment on your question: "is this a code challenge? If not.. why?"
You can't just print "hello world" without MAIN method and also without using STATIC and FINAL key word in java because the main method is a function required you don't have to apply any rocket science in that thing if u are using intelliJ IDEA or any other IDE anyways this is the code
public class Basics_Of_Java {
public static void main(String[] args) {
System.out.println("Hello world");
basics of java in 1st line is the name of the java file you may have another name.

List the names of methods being invoked

I'd like to have a reflection-like solution for displaying the methods which are called.
Example:
public class Foo {
public void bar() {
new Y().x();
}
}
public class Y {
public void x() {
}
}
public class Main {
public static void main(String[] args) {
// SETTING UP THE MAGIC
new Foo().bar();
new Y().x();
}
}
The output should be:
1. Foo.bar
1.2 Y.x
2. Y.x
Optimally there could be an event handler which would be fired every time a method is called(and some info could be passed as a parameter).
PS: I don't want to use this in a production environment, I only need this for displaying output in a skeleton app without dummy copy-paste.
I would use aspectj to define an aspect which writes log messages for every method call. You can find an example here: Tracing Java Method Execution with AspectJ. or here: Logging with AspectJ
The advantage of this solution is that you don't have to make any changes on your code. You will need some time to get into aspectj, but it meets your requirement very well.
You would have to build a profiler agent if you wanted to achieve this without having to pollute your code.
Take a look at this article, it shows you how to do it. Specifically, look at profiling aspects lower in that article.
Listing 2 is a profiling aspect that can be used to output the class name, method name, and a timestamp every time the JVM enters or leaves a method.

How to switch Display between different classes in Java ME

I am developing a Java ME program. The different forms are located in separate classes. I tried to switch display between main MIDlet and a class and succeeded. How to do the same between two classes? I am just a beginner in Java ME.
I use following code for the same,
First display a static Display variable in Midlet
private static Display display;
Now initialize the dislplay variable in class Constructor
public MyMidlet() {
display = Display.getDisplay(this);
}
Now declare a getDisplay() method in Midlet class
public static Display getDisplay () {
return display;
}
Now you can use this getDisplay() method to get the current Display's object and then set any class's form
MyMidlet.getDisplay().setCurrent(form);
Simplification is:
Display.getDisplay(this).setCurrent(screen);
Where screen is an instance of LCDUI (Form, Alert...) or intance of Canvas object.
The this is an instance of the MIDlet

"Component cannot be instantiated" in Netbeans 7.0.1

EDIT: Sorry, I just started programming in Java. It turned out to be a problem with an out of range array access... I am used to error messages about this kind of thing being automatic...
(using Netbeans 7.0.1)
I have been customizing JTextArea and JTable. I do so by adding a new Java class to my project and then declaring it extends the particular class I want (in my case, either JTextArea or JTable).
I had been using it normally, adding these new classes to JDialogs and JInternalFrames without any problem. I do so by just dragging it to my JDialog or JInternalFrame...
But recently, for some reason, I started getting this error messages "Component cannot be instantiated. Please make sure it is a JavaBeans component."
The JInternalFrames that were accepting the old customized classes still accepts them. But if I try to add the new customized class, it gives me that error message and, afterwards, it starts showing the same message to the old customized classes too...
Something really weird is going on. I copied the same code of a (previously) customized class to a new class (changing the name of the class, of course). Then I try to add this to my JInternalFrame. It gives me the error message! If, before this, I try to add the same customized class (with the original name), it adds the class normally....
This is annoying and I can't solve it. Can anyone help me please?
Thanks a lot for this answer but, if you want to know the reason here you are.
Typically this appears on two position:
an overridden method on your component.
a normal method on your component.
For example:
package UI.Components;
public class LabelComponent extends javax.swing.JLabel {
private javax.swing.JLabel label;
public TextFieldComponent() {
label = new javax.swing.JLabel(_label);
add(label);
}
#Override
public void setText(String text) {
label.setText(text);
}
}
The method setText(String text) is called say in the supper class constructor then it the overridden new method would be called in the case of the (label) variable which is used on this method still no being initialized so a java.lang.NullPointerException will be thowed.
solution:
1) try ... catch:
#Override
public void setText(String text) {
try {
label.setText(text);
} catch (Exception e) {
}
}
2) check:
use null initialization on declaration
private javax.swing.JLabel label = null;
then check on the method
#Override
public void setText(String text) {
if(label != null)
label.setText(text);
}
3)use initialization on declaration:
private javax.swing.JLabel label = label = new javax.swing.JLabel();
and then use setText method in your constructor
label.setText(_label);
note:
in the case of reason (2) a normal method on your component, it is the same as (1) but you may call the method before initialize the variable or assign null to the variable before calling the method and so on and it can being solved by the same ways.
I too faced the same problem, after some search in the web I found the solution for this problem. I don't have a deep understanding of why and how this problem occurs, but I can share with you the solution I found.
When you get such error msg, goto the menu View-->IDE Log or you can open the log from windows_user_Home\.netbeans\7.0\var\log
In that log you have to locate the error msg you got, for example,
INFO [org.netbeans.modules.form.BeanSupport]: Cannot create default instance of: test.Application1
java.lang.NullPointerException
at test.Application1.initLabel(Application1.java:906)
So the problem is in line 906 of your .java file. Open that file and comment those lines and then you will able to overcome the problem.
You can add the component to the Form or jInternalFrame or ...
After adding the component, you can again uncomment those lines. Just Clean and Build your project.
Hope this helps..
Goodluck
reachSDK
I have encountered the similar problem, however in different context.
I have two separate projects, a swing built user interface, and another one that poses as class library.
I added a class to the class library, headed over to the user interface, and implemented this newly added class from the library into the swing interface project in shape of an existing custom JFrame. So what happened to me now that the class loader of course could not find the class because the library project required compiling. The issue was fixed by compiling it.

Problem with basic listener behaviors in Java

It's a little embarassing to not know how to fix this on my own, seeing how I have a bit of experience with Java, however until now I've never really done anything other than web programming with Java.
I'm trying to create a wizard, and trying to generalize creation of the fields presented in the window. As such, I don't have direct control over the actual component JTextField but a wrapper class which handles the finer details. However I would like to know when the value has changed, so I've added a "addVetoableChangeListener" method which allows me to register a VetoableChangeListener to the JTextField itself.
I've verified that the method gets called and that it passes the listener onto the JTextField in debug. However, nothing gets called. No exception is launched, and my breakpoint inside the method which implements the interface VetoableChangeListener is never called.
Is there something I'm not getting? Does the listener have to be some sort of component before it works correctly or does it simply have to implement the interface? Perhaps I'm overlooking an obvious error because I've been concentrating on it for too long, and I'm hoping it'll be evident to one of you. A simpler version of what I'm attempting is:
public class TomcatConfigPanel extends WizardKeyValuePanel implements VetoableChangeListener {
protected void initPanel(JPanel mainPanel) {
addField("port", "8080");
IWizardField portField = getField("port");
portField.addVetoableChangeListener(this);
}
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
// Stuff that would drive you Lovecraft insane if you saw what was written here
}
}
public class WizardTextField implements IWizardField {
private JLabel label;
private JTextField field;
public WizardTextField() {
// some initialization stuff ...
}
public void addVetoableChangeListener(VetoableChangeListener listener) {
field.addVetoableChangeListener(listener);
}
}
The VetoableChangeListener will only be called if a constrained property is being changed on the JTextField. A constrained property is a property whose setter method throws a PropertyVetoException. So, if your code never calls any such setter method on the JTextField, your listener won't ever be called. Read http://download.oracle.com/javase/tutorial/javabeans/properties/constrained.html for more details.
I haven't found any constrained property in JTextField (and in all its class hirarchy) in the API doc, so I doubt your listener could ever be called.

Categories