I have an operations class that has no gui. The class basically does data management. The class is called from a method in my Main GUI. The problem I am having is with displaying messages to the user if something fails. I am using MessageDialog, but it keeps failing at runtime. I think the issue is with Shell. When I try to use null as the shell.
MessageDialog.openError(null, "Printer Error Message", "Error getting print reply file.");
The error is null pointer exception
MessageDialog.openError(Display.getCurrent().getActiveShell() etc
The error is null pointer exception
MessageDialog.openError(Display.getDefault().getActiveShell()
The error is invalid thread access
Being this is not a GUI class, do I have to pass in the shell from the GUI parent?
Can I just create a shell in the class and then use that?
You can fix the ERROR_THREAD_INVALID_ACCESS error with Display.syncExec or Display.asyncExec . Try with:
Display.syncExec(new Runnable() {
void run() {
MessageDialog.openError(Display.getDefault().getActiveShell()...
}
}
This will do what you want:
MessageDialog.openError(new Shell(), "Printer Error Message", "Error getting print reply file.");
Just create a new Shell and pass it to the MessageDialog.
Few important points to consider.
First of all, do not mix Data Management classes(models) with UI.
Have a utility class and methods to show errors/info messages.
always access UI widgets in UI thread. Use Display.getDefault().asyncExec() or syncExce()
Check Display.getDefault().getActiveShell() to pass it to the
dialog first, if it is null, create one and pass it.
Related
So I am trying to get the currently focused window using KeyboardFocusManager, I made two methods to try and achieve this:
public static void getWindowName() {
String WindowName = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow().toString();
System.out.println("Currently opened window: "+WindowName);
}
This results in Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.awt.Window.toString()" because the return value of "java.awt.KeyboardFocusManager.getFocusedWindow()" is null
and
public static Window getActiveWindow() {
return KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
}
When calling this method using System.out.println(getActiveWindow());, null gets print out to the console. I always have intelliJ opened and focused when executing the program, I even tried to focus another program, the task manager, same results. Does this happen to you too? What can I do to solve this or are there other, better and easier methods to get the currently focused window in java? I am using java 15.0.2 on windows 10
As java doc said, "getFocusedWindow() return null if the focused Window is not a member of the calling thread's context" then it may happened when you call it from another thread. So, to make sure getFocusedWindow() is fine, try to do focus programmatically:
some_focusable_component.requestFocus();
System.out.println("Currently opened window: "+KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow().toString() );
I would like to ask about how can I add some text on the screen.
I have button, when I click on that, I create new object. It has a function which provide some data for me.
How can I acces that data from the gui? I cannot have a getter because it gives me data after some time(after connection to the server).
Is there possibilit to put text to textEdit within the object created inside of gui class?
thanks
I adding the code, explaining a little more, sry for confusing, thx for trying to help:
I have EchoClient object created inside of gui class:
void Comunication::startListening(){
if (this->client == NULL)
{
this->client = new EchoClient(QUrl(QStringLiteral("ws://localhost:1234")), 0);
QObject::connect(client, &EchoClient::closed, this, &QApplication::quit);
}
else
qWarning() << "Carefull, the client is already running";
}
then in my EchoClient i have function
void EchoClient::onTextMessageReceived(QString message)
{
if (!m_debug)
qDebug() << "Message received:" << message;
HERE I would like to change the ui stuff.
}
Yes, It's possible. But your question at the moment seems too broad or unclear [at least] to me. I assume that you're using Qt Creator with its designer. So you should be able to access a ui object (in your MainWindow class). Having this object in hand you can change UI at anytime and at anywhere.
So, first assign that text box (i.e. QLineEdit) an id (for example myLineEdit). Now, ui->myLineEdit gives you a QLineEdit * which is actually a reference to that text box. So wherever you'd like to update UI, you should have that reference. For example if you're using TCP socket programming for contacting remote services, in onReadyRead signal of a QTcpSocket, you can update the text box with data you just received:
QLineEdit *textbox = ui->myLineEdit;
textbox->setText("updated data");
I solved this problem with a getter and setter and another button
First button: start listening...creates EchoClient object, this opens the websocket, connects to websocket server. In case the message has arrived from server it goes to method from EchoClient class called onTextMessageRecieved, there it sets atribute message to the value of incoming message.
void EchoClient::onTextMessageReceived(QString message)
{
if (!m_debug)
qDebug() << "Message received:" << message;
setData(message); //setting atribute message
}
Second button: get data... this will call get method from EchoClient class. Comunication is my gui class.
void Comunication::on_getData_clicked()
{
ui->textEdit_2->setText(this->client->getData());
}
But this solution is not good enough, could yo please advice how to make it that as soon as there is new message my textEdit will be automaticly updated?
Should I do it in another thread? I dont have much experiences.
Thanks.
If my app crashes, it hangs for a couple of seconds before I'm told by Android that the app crashed and needs to close. So I was thinking of catching all exceptions in my app with a general:
try {
// ...
} catch(Exception e) {
// ...
}
And make a new Activity that explains that the application crashed instantly (and also giving users an opportunity to send a mail with the error details), instead of having that delay thanks to Android. Are there better methods of accomplishing this or is this discouraged?
Update: I am using a Nexus 5 with ART enabled and I am not noticing the delay I used to experience with apps crashing (the "hanging" I was talking about originally). I think since everything is native code now, the crash happens instantly along with getting all the crash information. Perhaps the Nexus 5 is just quick :) regardless, this may not be a worry in future releases of Android (given that ART is going to be the default runtime in Android L).
Here, check for the link for reference.
In here you create a class say ExceptionHandler that implements java.lang.Thread.UncaughtExceptionHandler..
Inside this class you will do your life saving stuff like creating stacktrace and gettin ready to upload error report etc....
Now comes the important part i.e. How to catch that exception.
Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
Your Activity may look something like this…
public class ForceClose extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setContentView(R.layout.main);
}
}
You could just use a generic alert dialog to quickly display error messages.
For example...
//******************************************
//some generic method
//******************************************
private void doStuff()
{
try
{
//do some stuff here
}
catch(Exception e)
{
messageBox("doStuff", e.getMessage());
}
}
//*********************************************************
//generic dialog, takes in the method name and error message
//*********************************************************
private void messageBox(String method, String message)
{
Log.d("EXCEPTION: " + method, message);
AlertDialog.Builder messageBox = new AlertDialog.Builder(this);
messageBox.setTitle(method);
messageBox.setMessage(message);
messageBox.setCancelable(false);
messageBox.setNeutralButton("OK", null);
messageBox.show();
}
You could also add other error handling options into this method, such as print stacktrace
i found the "wtf" (what a terrible failure) method in the Log class. From the description:
Depending on system configuration, a report may be added to the
DropBoxManager and/or the process may be terminated immediately with
an error dialog.
http://developer.android.com/reference/android/util/Log.html
I am using the NetBeans GUI Builder to create a small application. To begin, let me just say that I can code everything by hand and solve this problem right away. However, I want to learn how to use the GUI Builder. This is my warning that all suggestions to not use it will get a down vote.
With that said, my current situation is that I have several JFormattedTextFields where I want to display an error message if the user enters data with an invalid format. The logic is the same in every case. The only difference will be to display a different error message depending on the exact formatting expected (i.e. a four digit year, a positive integer, etc.). I would like to simply write one listener that can be reused for every text field. I wrote the following method for the first text box:
private void formattedTextFieldFocustLost(java.awt.event.FocusEvent evt) {
JFormattedTextField source = (JFormattedTextField)evt.getComponent();
if (!source.isEditValid()) {
// TODO: Need a better error message.
JOptionPane.showMessageDialog(this, "Invalid input.", "Input Error", JOptionPane.ERROR_MESSAGE);
source.requestFocusInWindow();
}
}
The method signature is generated by NetBeans and is called from a generated of an anonymous inner class which extends FocusAdapter. Now when I go to the Design view in NetBeans and click on the combo box for the focusLost event of another component, this method name doesn't show up.
I also tried to create a named inner class which extends FocusAdapter. This doesn't show up in the event handler comboboxes, either.
What do I do to create a single method for all of my text fields?
If you have written the handler already, say btnActionPerformed, copy the name.
In design view, right-click the component where you want to attach the handler > Properties > Events > "..." button > Add > paste existing handler name in blank field and click OK.
(Netbeans 7.3.1)
Create your own method, e.g. validate():
private void validate(JFormattedTextField source) {
if (!source.isEditValid()) {
// TODO: Need a better error message.
JOptionPane.showMessageDialog(this, "Invalid input.", "Input Error", JOptionPane.ERROR_MESSAGE);
source.requestFocusInWindow();
}
}
then call this method from the individual listeners that you define through the GUI Editor:
private void formattedTextFieldFocustLost(java.awt.event.FocusEvent evt) {
JFormattedTextField source = (JFormattedTextField)evt.getComponent();
validate(source);
}
I am designing an application which shows unhandled exception due to lot of reason. So I want my application to show alert in catch block instead.
You could do something like this:
private Alert alert;
private Display display;
// Obtain display with display = Display.getDisplay(this); in consturctor
catch(Exception e) {
alert = new Alert("Error occurred", "Message: " + e.getMessage(), null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, form);
}
Hope this helps.
I think you can just put the alert handling in the catch block:
catch(Exception e) {
// create new alert and
}
The problem I think this guy is having, is that the exceptions are appearing seemingly randomly, i.e. he won't know which piece of code is throwing it.
Some J2ME handsets (e.g. Nokias) have a habit of showing the exception name to the user in an alert, while others (e.g. Sony Ericssons) silently swallow them.
You need to identify all the points at which code can be executed (i.e. all the threads you're creating, and all the MIDP lifecycle methods that the framework could be calling for you), and wrap all of those in try/catch blocks, to ensure that no exceptions can be shown in this way.
That will probably slow your code down a lot though, so you should get to the bottom of what causes these exceptions to appear, and fix the problem!