Clear TextField on button press - Java Applet - java

I have a Java Applet for login form. It has 2 TextFields, username and password. I need to clear them on clicking Reset button. This is the code I have written.
public class LoginForm extends Applet implements ActionListener
{
TextField name, pass, hidden;
Button b1, b2;
public void init()
{
name = new TextField(20);
pass = new TextField(20);
b2 = new Button("Reset");
add(name);
add(pass);
add(b2);
b2.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString("Hello", 10, 150);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.setText("");
pass.setText("");
repaint();
}
}
But this is not working properly.
Once I click the Reset button, the actionPerformed() method gets called and it also calls repaint(). (I can see "Hello" being displayed).
But the TextFields do not get cleared.
If I make following changes in actionPerformed
name.setText(" "); // please note the spaces
pass.setText(" ");
then it works. But I don't want spaces there. I want the TextFields to get blank.
Any help is appreciated.

Probably it is not good solution, but this is a workaround.Before setting the text invoke getText method and it will reset. Pretty strange! This behaviour is marked as Bug on this page
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.getText();
pass.getText();
name.setText("");
pass.setText("");
repaint();
revalidate();
}
Another solution would be setting text with space. But not if you have password-like fields which have setEchoChar('*').
public void actionPerformed(ActionEvent e) {
System.out.println(e);
name.setText(" ");
pass.setText(" ");
repaint();
revalidate();
}

just put blank in text fields.
public void actionPerformed(ActionEvent e) {
name.getText();
pass.getText();
name.setText("");
pass.setText("");
repaint();
revalidate();
}

Related

how to get a value from a Jcombobox array using a anonymous class

I have a array of Jradiobuttons.i am trying to have java anonymous class that implement ActionListener so when the user press on a radio button I can do something but since this is an array i cant give the array index using a while loop so how to identify what Jradiobutton I am using.and I want to get the text of that radio button and save it in a another variable...How can I do this?
This is what so far I have done :
if(count!=0) {
rs=pst.executeQuery();
JRadioButton a []=new JRadioButton[count];
jPanel3.setLayout(new GridLayout());
int x=0;
ButtonGroup bg=new ButtonGroup();
while(rs.next()) {
a[x]=new JRadioButton(rs.getString("name"));
bg.add(a[x]);
jPanel3.add(a[x]);
a[x].setVisible(true);
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,a[x].getText()); //here i cant use this x...even though i make x global value of x always will be 6 becouse of while loop.
}
});
x++;
}
}
If i understand you correctly, You can set the name of radio button:
a[x]=new JRadioButton(rs.getString("name"));
a[x].setName(rs.getString("name"));
and in ActionPerformed you get the source of action:
public void actionPerformed(ActionEvent e) {
if( e.getSource() instanceof JRadioButton){
String selectedRadioName = ((JRadioButton) e.getSource()).getName();
JOptionPane.showMessageDialog( null, selectedRadioName );
}
You could...
Supply each JRadioButton with a ActionCommand which will be made available via the ActionEvent
a[x]=new JRadioButton(rs.getString("name"));
a[x].setActionCommand(String.valueOf(x));
//...
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
int value = Integer.parseInt(cmd);
JOptionPane.showMessageDialog(null, a[value].getText());
}
});
See How to Use Buttons, Check Boxes, and Radio Buttons for more details
You could...
Use the Action API to surround the message and action in a self contained unit of work...
public class MessageAction extends AbstractAction {
private String message;
public MessageAction(String text, String message) {
this.message = message;
putValue(NAME, text);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, message);
}
}
And then apply it to your button something like...
a[x] = new JRadioButton(new MessageAction(rs.getString("name"), "Hello from " + x);
See How to Use Actions for more details.

Does clicking on a JTextField call the actionPerformed method

I have multiple JTextFields and I want to see which one is selected within the program. At the moment it does not seem as though clicking on the JTextField calls an ActionEvent (is that how you phrase it?).
public void actionPerformed(ActionEvent ae){
if(e.getSource().equals(JTextField.class)){
current = (JTextField) e.getSource();
System.out.println(current);
}
}
A ActionListener will generally be triggered when the user "actions" the field, for most platforms/look and feels, this is triggered by the user pressing the Enter key.
I think what you're after is a FocusListener
Have a look at How to Write a Focus Listener for more details
If you just want to find out which component is currently focused, you could use the KeyboardFocusManager
Component focusedComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
Use can use addMouseListener too,
jtextField.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
...
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
Did you add the actionListener to the JTextFiled?
JTextField tf= new JTextfield();
tf.addActionListener(//class name goes there, if the actionListener is in a different class otherwise just say "this");

How to enable / disable buttons in java, eclipse?

How can I disable buttons with the press of one button and when the task that the button which has been pressed was assigned to has been done then I want all the buttons to be enabled. for example;
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Up Button");
}
});
DownButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Down Button");
}
});
LeftButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
UpButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Left Button");
}
});
RightButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
UpButton.setEnabled(false);
System.out.printline("Right Button");
}
});
I have tried to do it but it does not work. What I want is, for example, my Upbutton is printing out ("Up button"), so when a user presses this button I want all the other buttons to be disabled until it has finished doing the command that it was suppose to do, in this case print out a text but later on I will be adding things like adding up two user inputs e.g. I will have a button that will ask the user to type number 1 and then number 2 and then the computer will add them up and during this process I want all the buttons to be disabled expect the one that has been clicked on, until the user has given all numbers and the computer has given the output.
I hope I have explained myself properly, if not please let me know and I will try my best to give more information. Thanks in advance.
How about using Command objects? Each command object might have execute() and canExecute() methods at least. Then;
btnA.setEnabled( cmdA.canExecute() );
btnA.addActionListener( event-> {
cmdA.execute();
btnB.setEnabled( cmdA.canExecute() );
});
That seems right. Maybe you want them invisible instead of disabled...
In that case:
LeftButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DownButton.setVisible(false);
UpButton.setVisible(false);
RightButton.setVisible(false);
System.out.printline("Left Button");
HereĀ“s an example of something that works:
private void jButtonChangeChampActionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxPlayer.setEnabled(true);
jComboBoxChampion.setEnabled(true);
jButtonSelecionar.setVisible(true);
jButtonMagias.setVisible(false);
}
What if you try this:
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpButtonActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.printline("Up Button");
}
It works here...
If you want to Set the Button Disabled , You can use the
btnExample.setDisable(true); // This will disable the Button
btnBreak.setVisible(false); // This will make the button Disappear visually only.
Hope this help guys.
You have to first disable the other buttons, finish your task and then enable the buttons again.
For example:
UpButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
// first disable all other buttons
DownButton.setEnabled(false);
LeftButton.setEnabled(false);
RightButton.setEnabled(false);
System.out.println("Up Button");
// do rest of your tasks here.
// now enable them again
DownButton.setEnabled(true);
LeftButton.setEnabled(true);
RightButton.setEnabled(true);
}
});
Similarly, setup the Listeners for the other buttons.
Hope this helps!

How to delete text when a user clicks a JTextField?

In my program, the user writes something in a JTextField then clicks a 'generate' button, which triggers the characters in the JTextField to be drawn to a JPanel.
I would then like to clear all the text in the JTextField when the user clicks the JTextField again. I tried to achieve this by adding a FocusListener and an ActionListener to the JTextField, however my attempts did not work. Moreover, my implementation of the FocusListener gave an Unreachable Statement compiler error.
Is this possible to do in Java and if so how can I do this?
The code below is my ActionListener implementation.
dfaText = new JTextField(6);
dfaText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
generateLabel.setText("NOOOOO!!!");
dfaText.setText("");
isDfaDrawn = false;
canDraw = false;
repaint();
}
});
Add a mouse listener:
field.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
field.setText("");
}
});
Bear in mind this could get frustrating if the user legitimately clicks elsewhere and returns to the field. You may wish to maintain some state, e.g. only clear the field if the button has been clicked in the interim.
You can do this:
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField.setText("");
}
});
Just an addition to others' code.
public void textfieldMouseClicked(java.awt.event.MouseEvent evt) {
uname_tf.setText(null);
} //This will set the JTextfield blank on mouse click//
public void textfieldFocusLost(java.awt.event.FocusEvent evt) {
uname_tf.setText("Username");
} //This will bring back the default text when not in focus//
Hope it helps, Cheers!!!
If you want it just one Click on it to delete the text you can do like this :
textField.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
textFieldMousePressed(evt);
}
});
private void textFieldMousePressed(java.awt.event.MouseEvent evt) {
textField.setText("");
}
Add 1 line to you buttonMethod e.g:
txtfield.clear();
or set your txtfield to an empty string

JOptionPane.showMessageDialog wait until OK is clicked?

This might be a very simple thing that I'm overlooking, but I just can't seem to figure it out.
I have the following method that updates a JTable:
class TableModel extends AbstractTableModel {
public void updateTable() {
try {
// update table here
...
} catch (NullPointerException npe) {
isOpenDialog = true;
JOptionPane.showMessageDialog(null, "No active shares found on this IP!");
isOpenDialog = false;
}
}
}
However, I don't want isOpenDialog boolean to be set to false until the OK button on the message dialog is pressed, because if a user presses enter it will activate a KeyListener event on a textfield and it triggers that entire block of code again if it's set to false.
Part of the KeyListener code is shown below:
public class KeyReleased implements KeyListener {
...
#Override
public void keyReleased(KeyEvent ke) {
if(txtIPField.getText().matches(IPADDRESS_PATTERN)) {
validIP = true;
} else {
validIP = false;
}
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
if (validIP && !isOpenDialog) {
updateTable();
}
}
}
}
Does JOptionPane.showMessageDialog() have some sort of mechanism that prevents executing the next line until the OK button is pressed? Thank you.
The JOptionPane creates a modal dialog and so the line beyond it will by design not be called until the dialog has been dealt with (either one of the buttons have been pushed or the close menu button has been pressed).
More important, you shouldn't be using a KeyListener for this sort of thing. If you want to have a JTextField listen for press of the enter key, add an ActionListener to it.
An easy work around to suite your needs is the use of showConfirmDialog(...), over showMessageDialog(), this lets you take the input from the user and then proceed likewise. Do have a look at this example program, for clarification :-)
import javax.swing.*;
public class JOptionExample
{
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
int selection = JOptionPane.showConfirmDialog(
null
, "No active shares found on this IP!"
, "Selection : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.INFORMATION_MESSAGE);
System.out.println("I be written" +
" after you close, the JOptionPane");
if (selection == JOptionPane.OK_OPTION)
{
// Code to use when OK is PRESSED.
System.out.println("Selected Option is OK : " + selection);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Code to use when CANCEL is PRESSED.
System.out.println("Selected Option Is CANCEL : " + selection);
}
}
});
}
}
You can get acces to the OK button if you create optionpanel and custom dialog. Here's an example of this kind of implementation:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author OZBORN
*/
public class TestyDialog {
static JFrame okno;
static JPanel panel;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
zrobOkno();
JButton przycisk =new JButton("Dialog");
przycisk.setSize(200,200);
panel.add(przycisk,BorderLayout.CENTER);
panel.setCursor(null);
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
przycisk.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor"));
final JOptionPane optionPane = new JOptionPane(
"U can close this dialog\n"
+ "by pressing ok button, close frame button or by clicking outside of the dialog box.\n"
+"Every time there will be action defined in the windowLostFocus function"
+ "Do you understand?",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION);
System.out.println(optionPane.getComponentCount());
przycisk.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final JFrame aa=new JFrame();
final JDialog dialog = new JDialog(aa,"Click a button",false);
((JButton)((JPanel)optionPane.getComponents()[1]).getComponent(0)).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
aa.dispose();
}
});
dialog.setContentPane(optionPane);
dialog.pack();
dialog.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Zamykam");
aa.dispose();
}
#Override public void windowGainedFocus(WindowEvent e) {}
});
dialog.setVisible(true);
}
});
}
public static void zrobOkno(){
okno=new JFrame("Testy okno");
okno.setLocationRelativeTo(null);
okno.setSize(200,200);
okno.setPreferredSize(new Dimension(200,200));
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel();
panel.setPreferredSize(new Dimension(200,200));
panel.setLayout(new BorderLayout());
okno.add(panel);
}
}
Try this,
catch(NullPointerException ex){
Thread t = new Thread(new Runnable(){
public void run(){
isOpenDialog = true;
JOptionPane.setMessageDialog(Title,Content);
}
});
t.start();
t.join(); // Join will make the thread wait for t to finish its run method, before
executing the below lines
isOpenDialog = false;
}

Categories