I am using Eclipse Photon 2018 and making a simple project using Java.
I started to use JOptionPane and for some reason - the size is tiny, as you can see in the image below:
My code:
Main.java:
public class Main {
public static void main(String[] args) {
Messageable ui = new GrapghicalUI();
String res = ui.getString("what is your name? ");
ui.showMessage("hi" +res);
}
}
ConsuleUI.java:
import java.util.Scanner;
public class ConsoleUI implements Messageable{
private Scanner s = new Scanner(System.in);
#Override
public void showMessage(String str) {
System.out.println(str);
}
#Override
public String getString(String msg) {
System.out.println(msg);
return s.next();
}
}
GraphicalUI.java:
import javax.swing.JOptionPane;
public class GrapghicalUI implements Messageable {
#Override
public void showMessage(String str) {
JOptionPane.showMessageDialog(null, str);
}
#Override
public String getString(String msg) {
return JOptionPane.showInputDialog(msg);
}
}
Messageable:
public interface Messageable {
void showMessage(String str);
String getString(String msg);
}
It's quite possibly a problem with Windows application scaling on a high DPI monitor. Usually it can be fixed by enabling "Override High DPI scaling behavior" under the compatibility tab of the properties of an executable file.
This question was posted on Microsoft support and can be found here
Since the dialog you see is from a separate program from the IDE itself, the scaling won't match as it has nothing to do with it. However, setting the above mentioned option will most likely not be very helpful as the executable gets replaced each time you build/compile it.
Related
I'm currently coding a project Java in eclipse which has two classes. The first class (open) I use to send a specific string to my second class (viewer) and then run my second class. The second class (viewer) I have imported into my program in the form of a jar file. I have done it this way as class viewer is a pdf viewer that i created using apache PDFBox and class open sends the file to the viewer to use, but the file will be different depending on many conditions (that are not relevant) in class open. The point is that class open needs to be separate from class viewer and can not simply be two different methods in one class. I would like to know if there is a way for class open to know when class viewer has been closed, as currently I am using a while loop, which just eats up memory and is very inefficient. The code I have does currently work, but I feel there is a better way, perhaps using listeners. This is the code for closing class viewer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//and import swing components ect
Public class viewer extends javax.swing.JFrame
implements KeyListener,
ActionListener{
private javax.swing.JButton zoomIn;
private javax.swing.JButton zoomOut;
//and a bunch more swing components
public static boolean closed = false;
public static String fileName = "";
public viewer()
{
}
private void initComponents() throws IOException
{
addWindowListener(new java.awt.event.WindowAdapter()
{
#Override
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitApplication();
}
});
}
private void exitMenuItemActionPerformed(ActionEvent evt)
{
if( document != null )
{
try
{
document.close();
}
catch( IOException e )
{
throw new RuntimeException(e);
}
}
closed = true;
System.exit(0);
}
public static void main(String filename) throws Exception
{
fileName = filename;
viewer mainViewer = new viewer();
String[] splittedStr = fileName.split("/");
BASETITLE = splittedStr[splittedStr.length - 1];
if (fileName != null)
{
mainViewer.openPDFFile(fileName);
}
mainViewer.setVisible(true);
}
This is my code from class open:
public static void main(String[] args) throws Exception {
String fileName = "C:/Files/Test.pdf";
viewer.main(fileName);
while(viewer.closed == false)
{
if(viewer.closed == true)
{
System.out.print("The Viewer Has Been Closed");
}
}
}
I want to know when it is closed so I can delete the file on the local drive. Thanks for your help!
Either you pass a callback (e.g. a Runnable) as argument to viewer.main, like viewer.main(fileName, () -> System.out.print("The Viewer Has Been Closed")) and make sure that it is called when the process is done, or you do as you've done except that you sleep your main thread a short time in the while loop, like Thread.sleep(100).
okay so I actually found an answer to my question and I'll just post it in case someone else had the same problem as me. I added a interface to the open class with the method close as shown:
import mainpackage.viewer;
public class Open implements closeInterface{
public Open() { }
public static String fileName;
public static void main(String[] args) throws Exception {
fileName = "C:/Files/Test.pdf";
run();
}
#Override
public void close() {
System.out.print("The Viewer Has Been Closed");
}
public static void run() throws Exception
{
viewer view = new viewer();
view.main(fileName);
view.addListener(new Open());
}
}
This was my code for my interface:
package mainpackage;
public interface closeInterface {
public void close();
}
And this was the snipit of code for my Viewer class
public class viewer extends javax.swing.JFrame {
private static closeInterface Closed;
private void initComponents() throws IOException
{
addWindowListener(new java.awt.event.WindowAdapter()
{
#Override
public void windowClosing(java.awt.event.WindowEvent evt)
{
exitApplication();
}
});
}
private void exitApplication()
{
try
{
if( document != null )
{
document.close();
}
}
catch( IOException io )
{
//do nothing because we are closing the application
}
Closed.close();
this.setVisible( false );
this.dispose();
}
public void addListener(closeInterface closed){
Closed = closed;
}
}
Thanks for everyone's help!
Does Java have anything similar to C#'s Action type? Is Java 8 or Pre-Java 8 the way to go? Why or why not? I'm trying to avoid going down any rabbit holes. Please help me understand my options...
Statement:
Driver.NoWait(() => links = rowFindElements(ByLinkText(title)));
Methods:
public static void NoWait(Action action)
{
TurnOffWait();
action();
TurnOnWait();
}
public static void TurnOnWait()
{
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
}
public static void TurnOffWait()
{
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
}
UPDATE
Thanks to #Nick Y and a programmer at the office (who told me the history of Java pragmatics vs Java traditionalists). This is the outcome of my findings:
Feature Menu Class 1st Way Post Java 8
public class FeatureMenu
{
static WebElement sideTab;
public static void Expand()
{
try
{
Iframe.Default.SwitchTo();
Driver.NoWait(() -> sideTab = Driver.Instance.findElement(By.cssSelector("div.wijmo-wijsplitter-v-panel1-collapsed")));
sideTab.click();
Log.Info("Feature Menu Expanded.");
}
catch(Exception e)
{
Log.Error("[EXCEPTION CAUGHT] : FeatureMenu.Expand()");
throw(e);
}
}
}
Feature Menu 2nd Way Pre Java 8
public class FeatureMenu
{
static WebElement sideTab;
public static void Expand()
{
try
{
Iframe.Default.SwitchTo();
Driver.NoWait( new Driver.Action(){ public void apply(){
sideTab = Driver.Instance.findElement(By.cssSelector("div.wijmo-wijsplitter-v-panel1-collapsed"));
}
});
sideTab.click();
Log.Info("Feature Menu Expanded.");
}
catch(Exception e)
{
Log.Error("[EXCEPTION CAUGHT] : FeatureMenu.Expand()");
throw(e);
}
}
}
Driver Class that can be used with either approach
public class Driver
{
public static WebDriver Instance;
public static String BaseAddress(String baseAddress)
{
return baseAddress;
}
public static void Initialize(String driverType)
{
Instance = new FirefoxDriver();
Instance.manage().window().maximize();
TurnOnWait();
}
#FunctionalInterface
public interface Action {
void apply();
}
public static void NoWait(Action action)
{
TurnOffWait();
action.apply();
TurnOnWait();
}
public static void TurnOffWait()
{
Instance.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
}
public static void TurnOnWait()
{
Instance.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
}
If you want to get closer to the most recent C# version you would want to use Java 8 (not pre-Java 8)
Java 8 has lambdas and functional interfaces which can get you very close to how things are done in C#. Google "functional interface java". There is a lot good information out there.
In the context of your specific question think about functional interfaces in java as delegates in C#.
public delegate void Action()
can be mimicked in java 8 as
#FunctionalInterface
public interface Action() {
void apply();
}
With this in mind, here is the simple usage of Action interface and lambda
public class MainWithAction {
public static void main(String[] args) {
noWait(() -> doSomething());
}
public static void noWait(Action action) {
turnOffWait();
action.apply();
turnOnWait();
}
public static void doSomething() { /* do something */ }
public static void turnOnWait() { /* skipped */ }
public static void turnOffWait() { /* skipped */ }
}
It is not a requirement to use #FunctionalInterface annotation but it helps compiler to generate error messages in certain cases.
apply() method name can be changed to anything else it is more of a convention thing.
Java 8 has a few predefined functional interfaces in package java.util.function however it appears that there is nothing that returns void and takes no parameters so you would need to have your own. Read more here:
https://softwareengineering.stackexchange.com/questions/276859/what-is-the-name-of-a-function-that-takes-no-argument-and-returns-nothing
You may want to consider having NoWaitAction interface which can be a more appropriate name for your scenario instead of a generic Action interface. It's up to you.
Having said all that I am moving to more interesting point of going down the rabbit hole.
Your particular use case may not map 100% into the java code. Let's try to convert this line.
Driver.NoWait(() => links = rowFindElements(ByLinkText(title)));
What caught my eye here is the links variable. It does look like a local variable to me. If this is not the case then the bellow is irrelevant, but may still trigger some thoughts.
For the sake of this exercise I am going to assume that links is a local variable of List of Strings type and rowFindElements takes String parameter and returns a List of Strings
Here is one way of converting this into java (with NoWaitAction as an example of my above point):
#FunctionalInterface
public interface NoWaitAction {
void apply();
}
and the meat
public class MainNoWaitAction {
public static void main(String[] args) {
List<String> links = new ArrayList<>();
String title = "title";
noWait(() -> links.addAll(rowFindElements(title)));
}
public static void noWait(NoWaitAction action) {
turnOffWait();
action.apply();
turnOnWait();
}
public static void turnOnWait() { /* skipped */ }
public static void turnOffWait() { /* skipped */ }
public static List<String> rowFindElements(String title) {
return new ArrayList<>(); // populate the list
}
}
There are various other ways of doing it, but the main point here is that the following will not compile
noWait(() -> links = rowFindElements(title));
Why? Read this answer for example
https://stackoverflow.com/a/4732617/5947137
Update 1
Based on OP comments I would like to suggest another approach
public class MainNoWaitAction {
public static void main(String[] args) {
List<String> links;
Object otherVariable;
String title = "title";
links = noWait(() -> rowFindElements(title));
otherVariable = noWait(() -> createAnObject());
}
public static <T> T noWait(Supplier<T> supplier) {
turnOffWait();
try {
return supplier.get();
} finally {
turnOnWait();
}
}
private static void turnOnWait() { /* skipped */ }
private static void turnOffWait() { /* skipped */ }
private static List<String> rowFindElements(String title) {
return new ArrayList<>(); // populate the list
}
private static Object createAnObject() {
return new Object();
}
}
Yes, you can write code the same way in Java :
public interface Action {
void apply();
}
public static void DoSomething(Action action)
{
action.apply();
}
public static void main(String[] args) throws IOException {
DoSomething(() -> System.out.println("test action"));
}
For performance wise, some people suggest use the following method, e.g.
public class MyActivity extends Activity {
private static final String TAG = "MyApp";
private static final boolean D = true;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "MyActivity.onCreate debug message"); }
But this is non-senese when are working on a large project, because when you debug, you need to update many files for the debug flag, are there any better method?
You can check the DEBUG boolean in your BuildConfig:
if (BuildConfig.DEBUG) {
// Do what you need
}
Or else, you can have a debug variable, but instead or keeping it in every activity, declare it in you Application class, and check it's value whenever you need.
If your purpose of that variable is for logging, is a good practice to wrap your loggings into another class, which checks the DEBUG variable:
public class LogUtils {
public static void LOGD(final String tag, String message) {
if (BuildConfig.DEBUG) {
Log.d(tag, message);
}
}
public static void LOGV(final String tag, String message) {
if (BuildConfig.DEBUG) {
Log.v(tag, message);
}
}
public static void LOGI(final String tag, String message) {
if (BuildConfig.DEBUG) {
Log.i(tag, message);
}
}
public static void LOGW(final String tag, String message) {
if (BuildConfig.DEBUG) {
Log.w(tag, message);
}
}
public static void LOGE(final String tag, String message) {
if (BuildConfig.DEBUG) {
Log.e(tag, message);
}
}
}
Then, make log calls to this class:
LogUtils.LOGD(TAG, "MyActivity.onCreate debug message");
I strongly recommend what Google guys developed at their open source app iosched. Among other reasons it keeps in mind BuildConfig and checks to see whether or not a log for the specified tag is loggable at the specified level with isLoggable. It's a must for my projects.
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import android.util.Log;
/**
* Helper methods that make logging more consistent throughout the app.
*/
public class LogUtils {
private static final String LOG_PREFIX = "iosched_";
private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
private static final int MAX_LOG_TAG_LENGTH = 23;
public static String makeLogTag(String str) {
if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
}
return LOG_PREFIX + str;
}
/**
* WARNING: Don't use this when obfuscating class names with Proguard!
*/
public static String makeLogTag(Class cls) {
return makeLogTag(cls.getSimpleName());
}
public static void LOGD(final String tag, String message) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
public static void LOGD(final String tag, String message, Throwable cause) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message, cause);
}
}
public static void LOGV(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message);
}
}
public static void LOGV(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message, cause);
}
}
public static void LOGI(final String tag, String message) {
Log.i(tag, message);
}
public static void LOGI(final String tag, String message, Throwable cause) {
Log.i(tag, message, cause);
}
public static void LOGW(final String tag, String message) {
Log.w(tag, message);
}
public static void LOGW(final String tag, String message, Throwable cause) {
Log.w(tag, message, cause);
}
public static void LOGE(final String tag, String message) {
Log.e(tag, message);
}
public static void LOGE(final String tag, String message, Throwable cause) {
Log.e(tag, message, cause);
}
private LogUtils() {
}
}
Another solution is found in one of the answers to this somewhat related question. You can override the Log class like this:
public class Log {
static final boolean LOG = false;
public static void i(String tag, String string) {
if (LOG) android.util.Log.i(tag, string);
}
public static void e(String tag, String string) {
if (LOG) android.util.Log.e(tag, string);
}
public static void d(String tag, String string) {
if (LOG) android.util.Log.d(tag, string);
}
public static void v(String tag, String string) {
if (LOG) android.util.Log.v(tag, string);
}
public static void w(String tag, String string) {
if (LOG) android.util.Log.w(tag, string);
}
}
This way, you don't need the if statement every time you use log. Just change the boolean in your overridden Log class. When you're ready to publish, you can use a tool like ProGuard to strip all the references to Log for performance.
Strip out Log.v and Log.d messages using ProGuard
An alternative approach, with less code, is to have these stripped out for the final release app using ProGuard.
Basically, in the app\proguard-rules.pro file, define the methods of the android.util.Log class that you want stripped out. The following addition to the proguard-rules.pro file will cause the v (verbose) and d (debug) methods to be stripped out at build time:
# This tell Proguard to assume Log.v and Log.d have no side effects (even
# though they do since they write to the logs) and thus can be removed
# during optimization:
-assumenosideeffects class android.util.Log {
public static int v(...);
public static int d(...);
}
This avoids the need for if (BuildConfig.DEBUG)-style checks peppered throughout the code.
Also see: Disable LogCat Output COMPLETELY in release Android app?
I've written a LogWrapper class which is simple and looks something like this:
public class LogWrapper {
private static final String DEBUG_TAG = "some-tag"
private static boolean logsEnabled;
public static void e(String msg) {
if (logsEnabled) {
Log.e(DEBUG_TAG, msg);
}
}
// other Log methods
}
You can use it instead of Log class, modifying the boolean variable as you wish in one place. Hope this helps.
I had the same problem recently, and I don't think that stripping off the classes with Proguard is a good idea to disable logs. So I ended up writing a simple drop-in replacement for the standard Android Log class
https://github.com/zserge/log
It allows you to control the log levels. It also gives you a lot of "sugar" for logging multiple values, for log tags and even more, and it all comes with only 200 lines of code available on Maven Central/JCenter.
I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it possible to create a custom event listener to detect this?
Please I cannot seem to find a solution to this anywhere and I found this website explaining how to create custom events
Use PropertyChangeSupport. You wont have to implement as much and it is thread safe.
public class MyClassWithText {
protected PropertyChangeSupport propertyChangeSupport;
private String text;
public MyClassWithText () {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public void setText(String text) {
String oldText = this.text;
this.text = text;
propertyChangeSupport.firePropertyChange("MyTextProperty",oldText, text);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
}
public class MyTextListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals("MyTextProperty")) {
System.out.println(event.getNewValue().toString());
}
}
}
public class MyTextTest {
public static void main(String[] args) {
MyClassWithText interestingText = new MyClassWithText();
MyTextListener listener = new MyTextListener();
interestingText.addPropertyChangeListener(listener);
interestingText.setText("FRIST!");
interestingText.setText("it's more like when you take a car, and you...");
}
}
Just like you need to create an event listener, you will also need to create the event firer -- since there is nothing automatic that will do this for you. I've provided sample code that shows you how to implement such a firer.
This test implementation isn't perfect. It only includes a way to add listeners. You may wish to include a way to remove listeners who are no longer interested in receiving events. Also note that this class is not thread-safe.
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class BooleanChangeTest implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() {
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
BooleanChangeTest test = new BooleanChangeTest(false);
test.addBooleanChangeListener(listener);
test.setFlag(false); // no change, no event dispatch
test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public BooleanChangeTest(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}
you can also try to implement an Observer.
First create the observable object:
import java.util.Observable;
public class StringObservable extends Observable {
private String name;
public StringObservable(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}
}
Then the observer:
import java.util.Observable;
import java.util.Observer;
public class NameObserver implements Observer {
private String name;
public NameObserver() {
name = null;
}
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
name = (String) arg;
System.out.println("NameObserver: Name changed to " + name);
} else {
System.out.println("NameObserver: Some other change to subject!");
}
}
}
And in your main (or wherever else):
public class TestObservers {
public static void main(String args[]) {
// Create the Subject and Observers.
StringObservable s = new StringObservable("Test");
NameObserver nameObs = new NameObserver();
// Add the Observer
s.addObserver(nameObs);
// Make changes to the Subject.
s.setName("Test1");
s.setName("Test2");
}
}
Mostly found here
Very late to answer, but this is a problem that can be solved with Observer/Observable. Example
The boolean you are setting should be allowed to do only through a setter method like:
public void setFlag(boolean flag){
//Method code goes here
}
Now in now set method, you can decide based on what value comes in, what event needs to be fired. I am explaining in simple terms without introducing complex terms so you can understand better, so code snippet would look like:
public void setFlag(boolean flag){
//if flag is TRUE do something
//If flag is FALSE then do something
//And finally do what you needed to do with flag
}
Ask questions if you need more info
you create a listener when you want to listen for I/O changes. mostly on graphics.
the answer to your question is to keep state of the running program, then check if variables change from the state inside the infinite loop of your program.
You can use AOP for that, perhaps AspectJ? Check a few examples here (if you use Eclipse, then using AspectJ is really simple with their plugin).
For you, you would have a pointcut similar to the one used in the SampleAspect, but one that will only be used when someone makes a new SET to a boolean variable (this doesn't mean that the value has changed, just that someone loaded a value to the variable).
my code, being practically identical to the code given in BlackBerry's tutorial, has a syntax error in Eclipse. i'm sure there is some small but i'm just not seeing, but my coworker could not find it as well. any ideas would be greatly appreciated. thanks!
Code:
pushScreen(new ABCScreen());
Error:
Cannot make a static reference to the
non-static method pushScreen(Screen)
from the type UiApplication
here is the complete source:
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class AwesomeBBCalculator extends UiApplication {
public AwesomeBBCalculator() {
AwesomeBBCalculator app = new AwesomeBBCalculator();
app.enterEventDispatcher();
}
public static void main(String[] args) {
pushScreen(new ABCScreen()); // ERROR LINE
}
}
final class ABCScreen extends MainScreen {
public ABCScreen() {
super();
// add title
LabelField title = new LabelField("Awesome BlackBerry Calculator",
LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
setTitle(title);
}
public boolean onClose() {
Dialog.alert("Thanks for using the Awesome BlackBerry Calculator!\nGoodbye.");
System.exit(0);
return true;
}
}
The pushScreen method can only be called within an instance of UiApplication. You are trying to call it from a static main method. That does not work. Do this instead...
public void foo()
{
pushScreen(this);
}
public static void main(String[] args)
{
(new ABCScreen()).foo();
}
public void class1()
{
pushScreen(this);
}
public static void main(String[] args)
{
(new NewScreen()).class1();
}
try making an object for the ABCScreen class and then use it or u may try this also:
UiApplication.getUiApplication().pushScreen(new ABCScreen());