Hey JGO, before we start let me show you what I’m talking about
My question:
How can I prevent the user from clicking the “Send” button if the text field is empty?
I know this is done via JOptionPane.showOptionDialog which returns an int based on which button was clicked sooooo how can I do this?
My idea would be to make the JOptionPane.showOptionDialog show a custom JPanel that has buttons on it, and as soon as text is typed in the custom text field the button becomes visible to send, but this seems complex (easy, but complex) so I’m wondering if there’s a easier way to do this?
Here’s the code to show the popup:
execServerCMDButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Popup header.
String popupHeader = "Please enter a command:";
// Popup buttons. (Custom)
String[] options = { "Send", "Cancel" };
// Panel that will contain our label/textfield.
JPanel panel = new JPanel(new BorderLayout());
// Label that will go on our panel.
JLabel lbl = new JLabel(
"<html><b>Enter a command to execute:</b>
<span style='font-size:10'>(To view command type /commands)</span></html>");
// Textfield commands will be entered in.
JTextField txt = new JTextField(20);
// Add our label/txtfield to our panel.
panel.add(lbl, BorderLayout.NORTH);
panel.add(txt, BorderLayout.SOUTH);
// Finally show the popup asking for a command
int selectedOption = JOptionPane.showOptionDialog(
frame.getContentPane(), panel, popupHeader,
JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, options, txt);
// Check whether they clicked send/cancel.
if (selectedOption == 0) { // Send button
// Obtain the text from the field:
String command = txt.getText();
// Make sure there's something in the field :P
if (command == null || command.length() == 0) {
// There is no text in the field
// user just hit send... :/
commandTextArea.append("Unable to process command. (FIELD WAS EMPTY)\n");
} else {
// There is some text in the command field
// check if it's a valid command.
if (isValidCommand(command)) {
// TODO: Execute command :P
commandTextArea.append("Command executed: "+ command + "\n");
} else {
// Not a valid command
commandTextArea.append("Unable to process command. (INVALID COMMAND)\n");
}
}
} else if (selectedOption == 1) { // Cancel button
System.out.println("Command sending canceled");
}
}
});
Thanks for any help JGO