I've got a custom tree cell renderer that I'm using to render custom icons a JTree, and I really like the warning icon and the error icon that JOptionPane displays for both warning messages and error messages respectively. Obviously I can use the following code to get the icons for my own use, but this is way heavy handed and requires me to instantiate dialogs that I'm never going to use:
public class ValidationCellRenderer extends DefaultTreeCellRenderer {
private Icon warnIcon;
private Icon errorIcon;
public ValidationCellRenderer() {
JOptionPane optionPane = new JOptionPane(new Object(),
JOptionPane.WARNING_MESSAGE);
warnIcon = optionPane.getIcon();
optionPane = new JOptionPane(new Object(),
JOptionPane.ERROR_MESSAGE);
errorIcon = optionPane.getIcon();
}
}
There's got to be a better way to get these icons as a resource, but I'm not finding an easy way to do this from the Java API. Anyone have any suggestions?
We use them too via:
UIManager.getIcon("OptionPane.errorIcon")
UIManager.getIcon("OptionPane.warningIcon")
And if you want to know about all the icons and their names you can check out: UIManager Defaults
Related
I'm new of Java and I want to do a jDialog that is opening when I push a button in the main JFrame and show a message of error in this way:
I can't put the image in another way in NetBeans? I create in the source package a directory with the image and a try much thing:
jDialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
jDialog1.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/img/error_button.png")))));
jDialog1.pack();
jDialog1.setLocationByPlatform(true);
jDialog1.setVisible(true);
Is there a simple way to do this?
We can use an option pane for this. It includes its own icons according to the type of message (and look and feel).
Exception e = new Exception("Error!");
JOptionPane.showMessageDialog(f, e, e.getMessage(), JOptionPane.WARNING_MESSAGE);
I am looking to figure out how to set the text of a label on an external Application Window.
What I have:
I have two windows so far. The first one is the main application window that will appear when the user starts the program. The second window is another separate window that I have created specifically to display a custom error window.
The problem: I seem to be unable to call the label that I have created on the error window and set the text to something custom. Why? I want to be able to reuse this window many times! This window is aimed for things like error handling when there is invalid input or if the application cannot read/save to a file.
I was going to post screen shots but you need 10 rep for that. It would have explained everything better.
Here is the code for the label on the Error_dialog window:
Label Error_label = new Label(container, SWT.NONE);
Error_label.setBounds(10, 10, 348, 13);
Error_label.setText("Label I actively want to change!");
Here is the condition I would like to fire off when it is met:
if(AvailableSpaces == 10){
//Set the label text HERE and then open the window!
showError.open();
}
I have included this at the top of the class as well:
Error_dialog showError = new Error_dialog();
Just save the label as a field in your dialog class and add a 'setter' method. Something like:
public class ErrorDialog extends Dialog
{
private Label errorLabel;
... other code
public void setText(String text)
{
if (errorLabel != null && !errorLabel.isDisposed()) {
errorLabel.setText(text);
}
}
You will need to use your dialog like this:
ErrorDialog dialog = new ErrorDialog(shell);
dialog.create(); // Creates the controls
dialog.setText("Error message");
dialog.open();
Note: you should stick to the rules for Java variable names - they always start with lower case.
Further learn to use Layouts. Using setBounds will cause problems if the user is using different fonts.
I will start developing application for Windows. But I want to get rid of the cancel button and the typical Windows format like:
And I want it to look something like that, get rid of windows format and design my application in my own way.
So, will somebody suggest me, how to do that? I searched so much but cannot find any result.
If this app. is written using the Swing GUI toolkit, it is as simple as either using a JWindow, or calling Frame.setUndecorated(true).
Hard to tell what language your question is, here is answer for C++ for WinAPI:
Create your window like that:
HWND hWnd;
WNDCLASS WndCls;
// Create the application window
WndCls.style = CS_HREDRAW | CS_VREDRAW;
WndCls.lpfnWndProc = WndProcedure;
WndCls.cbClsExtra = 0;
WndCls.cbWndExtra = 0;
WndCls.hIcon = NULL;
WndCls.hCursor = LoadCursor(NULL, IDC_ARROW);
WndCls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
WndCls.lpszMenuName = NULL;
WndCls.lpszClassName = _T("WndClassName");
WndCls.hInstance = GetModuleHandle(NULL);
// Register the window class
RegisterClass(&WndCls);
hWnd = CreateWindow(_T("MyWnd"),
_T("WndClassName"),
WS_BORDER,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
::GetModuleHandle(0),
NULL);
and then:
::ShowWindow(hWnd, SW_SHOW);
SetWindowLong(hWnd, GWL_STYLE, 0);
you will have a white rectangle app which you will be able to paint however you like.
Also, you can spy on window styles using Spy++ from Visual Studio package
It's called the Titlebar. Hide it by removing the form border style.
this.FormBorderStyle= System.Windows.Forms.FormBorderStyle.None;
How do I go about creating what I describe below?
First, here is the basic look of my GUI:
When I click on Add New Account I want to have the GUI pop up a small window where the user can enter log-in credentials. I would need this information to be passed back into the main GUI, so I am lost as how to approach this.
The same goes for Preferences or Remove Account. How do I go about creating a "GUI Overlay" of sorts. Sorry, I can't figure out the correct terminology for the effect I am looking for.
I wanted to attempt to use JOptionPane's, but after some research this seemed like it was not the route to be taking.
I was also toying with the idea of creating a new JFrame when the action was preformed. How should this be approached?
Start by using dialogs over frames. Dialogs are designed to gather small pieces of information from the user.
I would create a separate component for each operation you want to perform. Within these components I would provide setters and getters to allow you to gain access to the information managed by the component.
From there I would either use a JOptionPane or JDialog to display the component to the user. The reason for using one over the other for me comes down to begin able to control the action buttons (Okay and Cancel for example). For something like the login dialog, I want to restrict the user from begin able to hit the Login button until they've provided enough information to make the attempt.
The basic follow would be something like this...
LoginDialog dialog = new LoginDialog(SwingUtilities.getWindowAncestor(this)); // this is a reference any valid Component
dialog.setModal(true); // I would have already done this internally to the LoginDialog class...
dialog.setVisible(true); // A modal dialog will block at this point until the window is closed
if (dialog.isSuccessfulLogin()) {
login = dialog.getLogin(); // Login is a simple class containing the login information...
}
The LoginDialog might look something like this...
public class LoginDialog extends JDialog {
private LoginPanel loginPane;
public LoginDialog(Window wnd) {
super(wnd);
setModal(true);
loginPane = new LoginPanel();
setLayout(new BorderLayout());
add(loginPane);
// Typically, I create another panel and add the buttons I want to use to it.
// These buttons would call dispose once they've completed there work
}
public Login getLogin() {
return loginPane.getLogin();
}
public boolean isSuccessfulLogin() {
return loginPane.isSuccessfulLogin();
}
}
The dialog is simply acting as proxy/container for the login pane.
This is, of course an overview, you will need to fill in the blanks ;)
Now, if you don't want to go to the trouble of creating your own dialog, you can take advantage of the JOptionPane instead.
LoginPanel loginPane = new LoginPanel();
int option = JOptionPane.showOptionDialog(
this, // A reference to the parent component
loginPane,
"Login", // Title
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, // You can supply your own icon it if you want
new Object[]{"Login", "Cancel"}, // The available options to the user
"Login" // The "initial" option
);
if (option == 0) {
// Attempt login...
}
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);
}