JOptionPane.showInputDialog does not open dialog box - java

I was able to use this code successfully until yesterday, but after that JOptionPane.showInputDialog does not launch the dialog box, be it any simple code.
I use 64 bit system and code was working fine.
I have tried reinstalling Java, selenium, eclipse but nothing helped..I seem to have been missing very small thing. it will be great help if anyone can tell what exactly am I missing.
Here is my code (however any simple code is not working)
public static void main(String[] a) throws Exception {
String[] choices = {
"Belk-Make New Config Changes",
"Belk-Bring Back to Original",
"JCP-Make New Config Changes",
"JCP-Bring Back to Original"};
System.out.println(choices);
String input = (String) JOptionPane.showInputDialog(null,
"What do you want to do...",
"SyPi Config Changes",
JOptionPane.QUESTION_MESSAGE,
null, // use default icon
choices, // Array of choices
choices[0]); // Initial choice
}

Related

Creating a Log-In Screen with Validation?

I'm creating a Java log-in screen for a scheduling program that uses one-way encryption. The program should work as follows:
If it's the first time opening the program, ever, a window will show up asking the user to enter a username and password, as well as a security question. This first time, the password will not be hidden by black circles. Instead, it will be shown in plain text.
Then, the three fields will be encrypted using a caesar/shift cipher of 3 spots, and the 'encrypted' values will be saved into a file called info.txt in the source folder of the program.
The user will then be redirected to a log-in page, where they will re-enter their username and password to log in. Here, the password field is fixed so that the letters show up as black circles(not sure what this is called). A new int variable called loginAttempts is declared and initialized with the value 0.
After the user hits 'log-in', the system will use the same encryption method for the log-in details entered and compare them to the encrypted information in the text file. If both values match, then the user will be re-directed to the main screen of the program, having been granted access.
If not, then loginAttempts increments. After the 5th time, this happens, the user will be asked their security question. If the answer this wrong the first time, they will be booted from the program.
I have a few questions, as I'm having trouble creating this.
The dialog boxes I'm using to produce error messages are very confusing, and not seeming to work. I got the code to use them straight from the Oracle website and I'm still having trouble-- NetBeans has informed me that it 'cannot find symbol' for showInputDialog(the method I'm using to display the error message), but it's not suggesting that I'm missing any imports.
String errorMessage = "Security Question: What was your favorite class in college?";
String s = (String) JTextField.showInputDialog(
null,
errorMessage,
"ERROR",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.WARNING_MESSAGE,
null,
securityAnswer);
The part that's given me an error is the word 'showInputDialog' itself, and I'm unsure why..? I would like for this particular dialog to appear with a text field in it so that the user can enter the answer to the security question in there. However, the code doesn't even seem to be working.
On the Oracle page, this is the code that is given that is supposed to show a dialog box with an input field:
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
null,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");
But the word frame creates an error in the Netbeans GUI, and I'm not sure why it doesn't work. All I want is to create a text box that looks like this:
but I don't know how to do that in a way that would work.
The way that I've set up my program, I've made multiple jFrame components(different classes), and I've set it up so that if you were to try and access a different frame, the frame you were currently on would turn invisible. For example:
(a user is on the main screen, and they click on a button that says 'Add Appointment.')
addAppointment a = new addAppointment();
a.setVisible(true);
a.setAlwaysOnTop(true);
this.dispose();
And this works for literally all of my program except for the log-in page!
public createUserPass() throws IOException {
String path="\\src\\Schedulemanager\\pkg\\info.txt";
file = new File(path); //creates new File
if (file.exists()) { //make a new file if it's not already existent
logIn loginPage = new logIn();
loginPage.setVisible(true);
loginPage.setAlwaysOnTop(true);
this.dispose();
this.setVisible(false);
} else {
file.createNewFile(); //creates the new file
initComponents();
}
}
This is the 'main' class in the program that will run if the .jar file is clicked. What it's supposed to do is check if the info.txt file exists. If it does, then obviously the user has already set login information, and it should close itself and open an instance of the logIn class, which is the jFrame that handles the log-in functions once the information has been set. However, it doesn't work! It opens the new logIn class, but it doesn't dispose of the original one where you set the information, to begin with.
It's crucial that the original jFrame is hidden so that the user can't just set a new password every single time they run the program! How can I fix this?
Please let me know if I need to clarify anything.

Set the initial directory in SWT FileDialog

I'm working on an Eclipse RCP project and need to let the user select some file.
For convenience, based on some conditions, the initial directory of the file choosing dialog should be set prior to opening it.
As I'm bound to Eclipse RCP / SWT, I am working with the org.eclipse.swt.widgets.FileDialog.
The documentation of this FileDialog points out to use the setFilterPath(String string)-method which should do exactly what I need (see documentation).
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.html"});
dialog.setFilterPath("c:\\temp");
String result = dialog.open();
Unfortunately it is not working, at least not "every time".
I have currently no installation to check on it, but I'm quite sure that the feature would work totally fine on a Windows 200/XP/Vista machine.
I am working with a Windows 7 machine and I think I am suffering from the behaviour described here for lpstrInitialDir.
At least, this is exactly the behaviour I am facing: The path is good the first time I open the dialog, but the second time, the path is initially set to the last chosen path.
This seems to be convenient in most cases, but it is not in mine.
Can this be right?
If so, have I any chance on changing the behaviour according to my needs?
Thanks for any helping answer!
I ran into the same problem on Windows 10 and found a solution that seems to be working for me. A code snippet from the DirectoryDialog led to the right direction:
if (filterPath != null && filterPath.length() > 0) {
String path = filterPath.replace('/', '\\');
char[] buffer = new char[path.length() + 1];
path.getChars(0, path.length(), buffer, 0);
if (COM.SHCreateItemFromParsingName(buffer, 0, COM.IID_IShellItem, ppv) == OS.S_OK) {
IShellItem psi = new IShellItem(ppv[0]);
/*
* SetDefaultDirectory does not work if the dialog has
* persisted recently used folder. The fix is to clear the
* persisted data.
*/
fileDialog.ClearClientData();
fileDialog.SetDefaultFolder(psi);
psi.Release();
}
}
The FileDialog misses this statement 'fileDialog.ClearClientData()'. My solution is to execute the following code before setting the path and open the dialog:
long [] ppv = new long [1];
if (COM.CoCreateInstance(COM.CLSID_FileOpenDialog, 0, COM.CLSCTX_INPROC_SERVER, COM.IID_IFileOpenDialog, ppv) == OS.S_OK) {
IFileDialog fileDialog = new IFileDialog(ppv[0]);
fileDialog.ClearClientData();
fileDialog.Release();
}
Now you can set the filterpath without Windows messing things up.
I found a simple Solution for the Problem you described (I had the exact same Problem).
Just rearrange the your code like this:
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterPath("c:\\temp"); // This line is switched with the following line
dialog.setFilterExtensions(new String [] {"*.html"});
String result = dialog.open();
Somehow the Order of the methods called is relevant.
Are you using the same FileDialog object when you re-open it?
I ran a few quick tests and found that, if you re-set the filterPath, the dialog opens in the correct location.
If I open the same object again, it starts in the previously selected location.

Why are the options reversed in my JOptionPane?

I am developing and running my Java application on OS X Mountain Lion, and I added "Yes" and "No" options to a custom dialog box. However, when I ran my application on Windows 7, I noticed that the "Yes" and "No" options were reversed. To fix this UI glitch, I added this code:
String msg = "Are you sure you want to cancel the selected bookings?";
String[] options = new String[] { "Yes", "No" };
int noOption = 1;
String os = System.getProperty("os.name").toLowerCase();
if ("mac os x".equals(os)) {
options = new String[] { "No", "Yes" };
noOption = 0;
}
int option =
JOptionPane.showOptionDialog(null, msg, "Confirm Unbooking",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options,
options[noOption]);
if (option == noOption) {
return;
}
Can someone tell me why I experienced the issue that I described in the first place? I have a feeling that it has to do with the L&F of the application. Thanks!
It is indeed a L&F feature that performs this (this is not a UI glitch). I would recommend not to change that for a better user-experience. Users expect application to be consistent on a platform. Windows & Linux are used to have buttons displayed from left to right, while MacOS are used to have buttons displayed from right to left.
See here two samples:
Windows:
MacOS:
See how on MacOS, the most important button is displayed on the far right, while it is the opposite on Windows.

How do I change the value of a JOptionPane from a PropertyChangeListener without triggering the listener?

I am trying to make a program to manage a group of sports players. Each player has an enum Sport, and SportManager has convenient factory methods. What I am trying to do is open a dialog that has a JTextField for a name and a combo box to choose a sport. However, I want to stop the user from closing the dialog while the text field is blank, so I wrote a PropertyChangeListener so that when the text field is blank, it would beep to let the user know. However, if the user puts in something in the text after setting off the beep, it doesn't trigger the listener and you can't close the dialog without pressing cancel because the value is already JOptionPane.OK_OPTION, and cancel is the only way to change JOptionPane.VALUE_PROPERTY. So I tried to add
message.setValue(JOptionPane.UNITIALIZED_VALUE);
within the listener. However this just closes the window right away without giving the user a chance to fill in the text field, presumably because it triggers the listener I just registered. How do I make it so that it will beep more than once and give the user a chance to fill in the field?
FYI newPlayer is the component I'm registering the action to.
Code:
newPlayer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object[] msg = new Object [4];
msg[0] = new JLabel("Name:");
final JTextField nameField = new JTextField();
msg[1]=nameField;
msg[2] = new JLabel("Sport: ");
JComboBox<Sport> major = new JComboBox<Sport>(SportManager.getAllSports());
msg[3]=major;
final JOptionPane message = new JOptionPane();
message.setMessage(msg);
message.setMessageType(JOptionPane.PLAIN_MESSAGE);
message.setOptionType(JOptionPane.OK_CANCEL_OPTION);
final JDialog query = new JDialog(gui,"Create a new player",true);
query.setContentPane(message);
query.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
message.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (query.isVisible()&& (e.getSource() == message)&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
if(nameField.getText().equals("")&&message.getValue().equals(JOptionPane.OK_OPTION)){
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
return;
}
query.dispose();
}
}
});
query.pack();
query.setVisible(true);
if(Integer.parseInt(message.getValue().toString())==JOptionPane.OK_OPTION){
players.add(new Player(nameField.getText(),(Sport)major.getSelectedItem()));
edited=true;
}
gui.show(players);
}
});
I don't think you can do it with JOptionPane but you can using using TaskDialog framework and few others.
You can also create a dialog yourself, attach change listeners to your fields and enable/disable OK button based on content of your fields. This process is usually called "form validation"
However, I want to stop the user from closing the dialog while the
text field is blank
I get where you are going, but Java Swing is not very good at this. There is no way you can prevent the listener from being called. A solution would be to ignore the call, but this is complicated to implement.
The way I solved this issue is to let the pop-up disappear, check the returned value and if it is null/empty, beep and re-open it until user fills something.
JOptionPane does not internally support validation of inputs (Bug Reference). Your best bet is to create your own custom JDialog which supports disabling the OK button when the input data is invalid.
I'd recommend reading the bug report since other people talk about it and give workarounds.
However, I want to stop the user from closing the dialog while the text field is blank
The CustomDialog example from the section in the Swing tutorial on Stopping Automatic Dialog Closing has a working example that does this.
After taking a quick look at your code and the working example I think your code should be something like:
if (query.isVisible()
&& (e.getSource() == message)
&& (prop.equals(JOptionPane.VALUE_PROPERTY)))
{
if (message.getValue() == JOptionPane.UNINITIALIZED_VALUE)
return;
if (nameField.getText().equals("")
&& message.getValue().equals(JOptionPane.OK_OPTION))
{
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
else
query.dispose();
}
Otherwise, I'll let you compare your code with the working code to see what the difference is.
One way to solve this problem is to add a Cancel and Ok button to your dialog. Then, disable closing the popup via the X in the corner, forcing the user to click either Cancel or Ok to finish/close the dialog. Now, simply add a listener to the text field that will disable the Ok button if the text field is blank.
Judging from your code I assume you can figure out how to implement these steps, but if you have trouble let us know! Good luck!

plugin development in eclipse

i have this problem with my project these days. i'm developing a plugin in eclipse,
i need to write a text on the active window(coding area) when i click a button.
i use the following code in my button.java class
public class Button implements IWorkbenchWindowActionDelegate {
private IWorkbenchWindow window;
/**
* The constructor.
*/
public Button() {
}
/**
* The action has been activated. The argument of the
* method represents the 'real' action sitting
* in the workbench UI.
* #see IWorkbenchWindowActionDelegate#run
*/
public void run(IAction action) {
MessageDialog.openInformation(
window.getShell(),
"Button",
"Code of the Button goes here");
}
how can i do it inside the run method? here I'm displaying a message, instead of showing a message i want to display some text in the text editor pane. please help me to achieve this.
if you guys can please give me some links to understand about eclipse plug-in developments? any blog posts that are easy to understand will be much better?
You should do something like this. It is completely untested and you will need to add lots of null checks and try-catch blocks, but the code below gets the currently active editor and replaces the current selection with whatever is passed in as an argument:
void method (String text) {
IEditorPart part = Workbench.getInstance().getWorkbenchWindows()[0].getActivePage().getActiveEditor();
IEditorInput editorInput = part.getEditorInput();
if (part instanceof ITextEditor) {
ITextEditor textEditor = (ITextEditor) part;
IDocument doc = textEditor.getDocumentProvider().getDocument(editorInput);
ITextSelection sel = textEditor.getSelectionProvider().getSelection();
doc.replace(sel.getOffset(), sel.getLength(), text);
}
}
It is messy and complicated, but that's the Eclipse framework for you.
This might be a good place for you to look at Eclipse plugin development:
http://www.ibm.com/developerworks/views/opensource/libraryview.jsp?search_by=Create+commercial-quality+eclipse+ide
Developer Works in general has a lot of good content on Eclipse, so if this series is not exactly what you need, you can explore Developer Works for other things.
I'd recommend this one. It is a very good introductory tutorial

Categories

Resources