Simple way to have a hybrid JTextField / JPasswordField? - java

I am developing a simple applet that has a simpe sign-in interface.
And to be concise in space, I have two JTextFields for username and password, which I also use as labels. i.e. to start with, the username JTextField will be pre-filled with grey text saying "username" and the password JTextField pre-filled with "simple password".
Then as soon as the JTextField gets focus, i clear the prefill text and set the text color to black. Similar to stackoverflow's search box, but in swing.
Now for security, I would like to mask the password field when the password JTextField gets focus (but of course still have the pre-filled text legible to start with). JPasswordField doesn't allow the toggling of mask/unmask.
Any ideas for a simple way to obtain this functionality in my simple applet?

You can disable the masking echo character with setEchoChar((char)0); as stated in the JavaDoc.
An example
final JPasswordField pass = new JPasswordField("Password");
Font passFont = user.getFont();
pass.setFont(passFont.deriveFont(Font.ITALIC));
pass.setForeground(Color.GRAY);
pass.setPreferredSize(new Dimension(150, 20));
pass.setEchoChar((char)0);
pass.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
pass.setEchoChar('*');
if (pass.getText().equals("Password")) {
pass.setText("");
}
}
public void focusLost(FocusEvent e) {
if ("".equalsIgnoreCase(pass.getText().trim())) {
pass.setEchoChar((char)0);
pass.setText("Password");
}
}});
Greetz,
GHad

The Text Prompt class will support a password field.

Related

How to change a String in a JTextArea - Java

I'm about to make a program where if you click a button it will show some text... But i don't know how to change the string after i have set the string. Here is the code i have right now.
//Text Area to "Copy"
String output = "";
JTextArea TArea = new JTextArea(output);
TArea.setBounds(200, 72, 177, 296);
panel.add(TArea);
//When press the button "Generate"
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
String output = "Hello World";
TArea.setBounds(200, 72, 177, 296);
}
});
Hope you can help me :)
But i don't know how to change the string after i have set the string
textArea.setText(...);
will reset the text
textArea.append(...);
will add text to the end of the text area.
Other thoughts:
I suggest you read the Swing Tutorial for the basics of using Swing.
Don't use setBounds(..). Swing was designed to be used with layout managers. The tutorial has plenty of examples of using the layout managers.
Variable names should NOT start with an upper case character. Follow Java conventions and don't make up your own. Any tutorial or text book will follow the conventions.

Is there a listener for a cursor being put into JTextField?

Here is my application. It's a wallet to update my money when I spend or get profit. Look it up on image hosting here http://tinypic.com/r/687bdk/8
Is there a way to detect that a cursor has been put into one of the JTextFields? If there is, then could I dispatch a method that would delete whatever is in the other JTextField? There should only be one JTextField with input, it is unacceptable to have inputs in both text fields.
You can add a FocusListener to each textfield i.e.
JTextField myTextField = new JTextField();
myTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
//when selected...
}
#Override
public void focusLost(FocusEvent e) {
//when not selected..
}
});
Is there a way to detect that a cursor has been put into one of the JTextfields? If there is, than I could dispatch a method that would delete whatever is in the other JTextField.
As a user I'm not too crazy about that design. I've used accounting type applications before where you have two columns (debit/credit) and a number can only be entered into one.
In those applications the number is not removed on focus, it is removed if a value is entered in the other field. This allows for tabbing between fields on the forum without data disappearing just because focus changes.
To implement this type of functionality you would add a DocumentListener to the Document of the text field. Then whenever text is entered into the Document the listener is invoked and you can clear the text from the other text field.
Check out the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.
It called: CaretListener
jTextArea=new JTextArea();
jTextArea.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e){
//your code
}
}
);
It mainly used when you need to know that your caret position is changed.

UI Java: Button which clears the data of a JTable

I am quite new to the creation of user interface in Java. I have been using the WindowBuilder to create an interface. I have some data from a table and I would like
The user to check if they are double or not and hit the right button (Double, not double)
Then, the variable double or the notdouble I would like to increase
And in the end, to have the table cleared from the data and display the next data from the table.
In the end, I would like to give the results of the variables (double, notdouble)
I have written a code for action listeners of the buttons, so far in
order to diplay some messages
// DOUBLE BUTTON
JButton btnDouble = new JButton("DOUBLE");
btnDouble.setFont(new Font("Calibri", Font.PLAIN, 12));
btnDouble.addActionListener(new ActionListener() { // For event handling
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the DOUBLE button");}
});
I am just writing here in order to give me some guidelines or where I should look for. Any tutorial available would be very helpful.
How to use Button and
How to use Table

Java Editable JCombobox Keylistener event for Enter key

I have editable JCombobox and I added keylistener for combobox editor component.
When user press 'Enter key' and if there is no text on the editable combobox I need to display message box using JOptinoPane. I have done necessary code in keyrelease event and it displays message as expected.
Problem is, when we get message box and if user press enter key on 'OK' button of JOptionPane, combobox editor keyevent fires again. Because of this, when user press Enter key on message box, JoptionPane displays continuously.
Any idea how to solve this?
Note that I can't use Action listener for this.
Please check if this code helps you!!!
JFrame frame = new JFrame("Welcome!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_ENTER) {
if (((JTextComponent) ((JComboBox) ((Component) event
.getSource()).getParent()).getEditor()
.getEditorComponent()).getText().isEmpty())
System.out.println("please dont make me blank");
}
}
});
frame.add(cmb);
frame.setLocationRelativeTo(null);
frame.setSize(300, 50);
frame.setVisible(true);
Most people find it difficult because of this casting.
We need to add a key listener on the component that the combo box is using to service the editing.
JTextComponent editor = (JTextComponent) urCombo.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
// your code
}
});
Hope this code helps.
Note that I can't use Action listener for this.
this doesn't make me any sence, then to use ItemListener
Any idea how to solve this?
never to use KeyListener for Swing JComponents, use (Note that I can't use Action listener for this.) KeyBindings instead,
notice ENTER key is implemented for JComboBox in API by default, have to override this action from ENTER key pressed
One option would be to replace the KeySelectionManager interface with your own. You want to replace the JComboBox.KeySelectionManager as it is responsible for taking the inputted char and returns the row number (as an int) which should be selected.
Please check the event ascii code by ev.getkeycode() and check if it is a number or character. If it is neither a number nor a character do nothing.
If it is what you want then do the process.
If you are using Netbeans then right click on your combobox and select customize code.
add following lines of code
JTextComponent editor = (JTextComponent) Code.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
if(evt.getKeyCode()==10)
//do your coding here.
}
});

If a new Frame show up setEditable(false) , If the user close it setEditable(true)

I want to create this code :
The user enter a numerical value , if he entered character it will throw exception
the field will stop working then another frame show up and display error message
after the user close the new frame , everything return to the way it is
that means the field will work again !
I managed to make the field stop working but I didn't know if the user closed the new frame or not !
here is my try
public void keyReleased(KeyEvent event) {
try{
double l,h,w;
l=Double.parseDouble(input_length.getText());
w=Double.parseDouble("0"+input_width.getText());
h=Double.parseDouble("0"+input_width.getText());
}
catch(NumberFormatException a){
input_length.setEditable(false);
input_height.setEditable(false);
input_width.setEditable(false);
JFrame ErrorFrame = new JFrame("Error");
JPanel content = new JPanel(); ;
ErrorFrame.setContentPane(content);
ErrorFrame.setSize (350, 150);
ErrorFrame.setResizable (false);
ErrorFrame.setLocation (FRAME_X_ORIGIN, 250);
content.setLayout(new FlowLayout());
JLabel text = new JLabel(" ERROR ! please Enter number only ",JLabel.CENTER);
text.setFont(new Font("Arial", Font.PLAIN, 20));
text.setForeground(Color.red);
content.add(text);
ErrorFrame.setVisible(true);
setDefaultCloseOperation(ErrorFrame.EXIT_ON_CLOSE);
int op = ErrorFrame.getDefaultCloseOperation();
if(op == 1 ){
input_length.setEditable(true);
input_height.setEditable(true);
input_width.setEditable(true);}
}
}
1). Do not use new JFrame for error message - use JDialog Here is how
2). h=Double.parseDouble("0"+input_width.getText()); i think that you meant input_height.getText() here, not input_width.getText()
3). After showing your error dialog just clear your text fields - it is ok. When user will close it - he will see them empty.
If you would opt for a modal dialog to show the error message, there is no need to change the editable state of your fields.
Personally as a user I would become quite irritated if a dialog was shown each time I made a typo. For example changing the background color of the text field to red on invalid input, and disabling the OK button (or whatever mechanism you have as user to indicate you are finished editing) is more user-friendly IMO. You can even show a label indicating the errors in your panel, or a tooltip, ... .
I would also recommend a DocumentListener instead of a KeyListener if you want to react on updates of the text in the text field
An example on why I propose to opt for another mechanism to inform the user of the error:
I paste an invalid value in the textfield (e.g. 3x456) and a dialog pops up. Now I want to use my arrow keys to navigate to the error and correct it. This means I have to navigate 3 positions to the left to delete the x. If I use my arrow keys (which are keys as well) I will see this dialog 3 more times during the navigation.

Categories

Resources