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);
Related
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.
Please help me in showing popup in front of browser. I have used following code, but it's coming behind browser once I clicked a save button.
JFrame frame;
frame = new JFrame("");
JOptionPane.showMessageDialog(frame, "Instance is already created");
You need to specify the window/frame as the first argument to show message dialog in front of that frame. So instead of passing null:
JOptionPane.showMessageDialog(null,
"Instance is already created");
pass the parent Frame
Ok so I've been researching this one quiet a bit. I am fairly new to java but thought that this one would be easy. Ive tried just about every way that has been answered on this site and still no luck, and usually when I look here I am able to find a answer that fits what I am looking for. Does anyone know how to change the Java icon in the top corner of the JFrame. I'm pretty positive that its not my file path either because all my images are in the same folder and they all work, this is the only one that I can't seem to get to work.
This is the first part my code for the main menu of my program, everything works except when i try to add the icon image. The code I've entered below does not have anything in it for the JFrame IconImage, I removed it since it didn't work. So if there is someone who knows how to get it working with this code that would be highly appreciated, thank you very much in advanced!
public class MainFrame
{
private MyPanel main;
private MyPanel2 create;
private MyPanel3 update;
private MyPanel4 find;
JFrame frame = new JFrame("Main Menu:");
public void displayGUI()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new CardLayout());
main = new MyPanel(contentPane, this);
create = new MyPanel2(contentPane);
update = new MyPanel3(contentPane);
find = new MyPanel4(contentPane);
contentPane.add(main, "Main Menu");
contentPane.add(create, "Create Part");
contentPane.add(update, "Update Part");
contentPane.add(find, "Find Part");
frame.setLocation(200, 200);
frame.setSize(700, 580);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
I have an answer for you. First, make sure that the images are in a folder, not a package. Next, insert this line of code:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/image.png"));
ImageIcon icon = new ImageIcon( );
setIconImage(icon.getImage());
This code gets the image from the class path, and returns it as a image icon, and then it sets it. This should add the image icon to the application. If it doesn't, then tell me.
EDIT: After you told me that that didn't work then I decided to take a second crack at it...
First, put your images into a completely separate folder. I usually call this /res. Next, put your image in there. Now, for loading I took a completely different route. I decided to use ImageIO instead of default loading. To load the image, you use this code:
try {
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
}
catch (IOException exc) {
exc.printStackTrace();
}
ImageIO works a lot better for loading images. If this still doesn't work then please tell me.
If you want to export this as a JAR then put a folder the same name as you used in the program in the same directory as the JAR.
For example in a NetBeans project, create a resources folder in the src folder.
Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource),
you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.
This works pretty fine for me.
Just add this after you've created your JFrame.
try {
Image image = new ImageIcon("/icons/image.jpg").getImage();
frame.setIconImage(image);
}catch(Exception e){
System.out.println("Application icon not found");
}
Paste your image icon (fav.png) in the same package first,
Write following code in constructor of JFrame:
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("fav.png")));
Note:- fav.png is the name of icon
this.setIconImage(new ImageIcon(getClass().getResource("/iconsfolder/iconsname.jpg")).getImage());
// sets the Global icon for the system
try this code put after this code:
public void displayGUI()
{
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'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