I'm facing problem with the simulation of the button click. I have JTextField that takes data from scanner (like in grocery stores). After that i need to push enter button, to activate function jTextField1ActionPerformed. Is there any way to do it without producing any button actions?
Or i need tip how to jButton1.doClick() every time jTextField is changed. Please help!:)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
AddEmployee.add(jTextField1.getText());
jLabel7.setText(AddEmployee.name);
jLabel12.setText(AddEmployee.dep);
jLabel10.setText(AddEmployee.pos);
jLabel11.setText(AddEmployee.time);
num++;
jName.append("\n"+Integer.toString(num)+". "+AddEmployee.name);
jTime.append("\n"+Integer.toString(num)+". "+AddEmployee.time);
jTextField1.setText("");
}
catch (ClassNotFoundException | SQLException | ParseException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to simulate the button press, including in the UI, you can call the following method:
myButton.doClick();
This will act as the user physically pressed it. Otherwise, you can create an ActionEvent and pass it to the button's listeners:
// Does not appear in the UI
for(ActionListener a: mybutton.getActionListeners()) {
a.actionPerformed(yourActionEvent);
}
In your case though(considering the code posted) I suggest making a method out of the button's code, and just call it wherever you want:
public void showData(){
try {
AddEmployee.add(jTextField1.getText());
jLabel7.setText(AddEmployee.name);
jLabel12.setText(AddEmployee.dep);
jLabel10.setText(AddEmployee.pos);
jLabel11.setText(AddEmployee.time);
num++;
jName.append("\n"+Integer.toString(num)+". "+AddEmployee.name);
jTime.append("\n"+Integer.toString(num)+". "+AddEmployee.time);
jTextField1.setText("");
}
catch (ClassNotFoundException | SQLException | ParseException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void myButtonActionPerformed(java.awt.event.ActionEvent evt) {
showData();
}
private void myOtherComponentEventOcurred(java.awt.event.ActionEvent evt) {
showData();
}
Related
I have a document listener that works just fine. However, I'd like to add some functionality to it so that when the user hits the Enter key, the focus shifts to another object. I can't figure out how to trap this. Here is my code:
txtNum1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
setAnswer(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
setAnswer(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
setAnswer(e);
}
private void setAnswer(DocumentEvent e) {
if (txtNum1.getText().equals("")) {
num1 = 0;
} else {
num1 = Integer.parseInt(txtNum1.getText());
}
calcAnswer();
System.out.println(e); //trying to output the event 'Enter'
}
I can do this with a key listener, but I've been scolded on this site before about using that approach, so I'm trying to learn this the correct way.
Thanks!
EDIT:
Per the suggestions below, I added the following code, but it seems to have no effect. Can anyone see what I am missing? Thanks!
/* If the user hits the Enter key, we want the focus to shift to
* the next text field */
txtNum1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
txtNum2.requestFocus();
}
});
On a JTextfield, you can trap the Enter key simply by adding an ActionListener. It will get fired when the users types enter
I am making a courier program in which the user can create a new account.
I want to have a next button that the user cannot press until the text fields have been filled in.
So a blank Name Field and Surname field would mean the next button cannot be pressed but if the fields have been filled in, the next button can be pressed
Add a KeyListener like this to your fields:
nameField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
if(nameField.getText().length() > 0 && surNameField.getText().length() > 0)
nextButton.setEnabled(true);
else
nextButton.setEnabled(false);
}
});
This will check if the two fields are not empty, every time a key has been pressed in the field. If the condition is true, the next button will be enabled.
In simple term, try something like.
String text = textField.getText();
if (text.length()>0)
button.setEnabled(true);
...
If you want to have the button enable on the fly then its a bit more complicated
EDIT :
complicated case:
Document textFieldDoc = myTextField.getDocument();
textFieldDoc.addDocumentListener(new DocumentListener() {
void changedUpdate(DocumentEvent e) {
updated(e);
}
void insertUpdate(DocumentEvent e) {
updated(e);
}
void removeUpdate(DocumentEvent e) {
updated(e);
}
private void updated(DocumentEvent e) {
boolean enable = e.getDocument().getLength() > 0;
myButton.setEnabled(enable);
}
});
In your actionPerformed method, for every actionEvent checking, check whether the required fields are filled up, if so, set your button setEnabled(true). Perhaps a better answer can be provided if you can show us your code.
I am following the Oracle tutorial on how to create a custom dialog box: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
I have two buttons: Save Object and Delete Object which when clicked should execute a certain piece of code. Unfortunately I can't seem to add any ActionListener to the JOptionPane buttons so when they're clicked nothing happens.
Can anyone help tell me how I can go about doing this? Here is the class I have for the dialog box so far:
class InputDialogBox extends JDialog implements ActionListener, PropertyChangeListener {
private String typedText = null;
private JTextField textField;
private JOptionPane optionPane;
private String btnString1 = "Save Object";
private String btnString2 = "Delete Object";
/**
* Returns null if the typed string was invalid;
* otherwise, returns the string as the user entered it.
*/
public String getValidatedText() {
return typedText;
}
/** Creates the reusable dialog. */
public InputDialogBox(Frame aFrame, int x, int y) {
super(aFrame, true);
setTitle("New Object");
textField = new JTextField(10);
//Create an array of the text and components to be displayed.
String msgString1 = "Object label:";
Object[] array = {msgString1, textField};
//Create an array specifying the number of dialog buttons
//and their text.
Object[] options = {btnString1, btnString2};
//Create the JOptionPane.
optionPane = new JOptionPane(array,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]);
setSize(new Dimension(300,250));
setLocation(x, y);
//Make this dialog display it.
setContentPane(optionPane);
setVisible(true);
//Handle window closing correctly.
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
/*
* Instead of directly closing the window,
* we're going to change the JOptionPane's
* value property.
*/
optionPane.setValue(new Integer(
JOptionPane.CLOSED_OPTION));
}
});
//Ensure the text field always gets the first focus.
addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent ce) {
textField.requestFocusInWindow();
}
});
//Register an event handler that puts the text into the option pane.
textField.addActionListener(this);
//Register an event handler that reacts to option pane state changes.
optionPane.addPropertyChangeListener(this);
}
/** This method handles events for the text field. */
public void actionPerformed(ActionEvent e) {
optionPane.setValue(btnString1);
System.out.println(e.getActionCommand());
}
/** This method reacts to state changes in the option pane. */
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (isVisible()
&& (e.getSource() == optionPane)
&& (JOptionPane.VALUE_PROPERTY.equals(prop) ||
JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
Object value = optionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
//Reset the JOptionPane's value.
//If you don't do this, then if the user
//presses the same button next time, no
//property change event will be fired.
optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if (btnString1.equals(value)) {
typedText = textField.getText();
String ucText = typedText.toUpperCase();
if (ucText != null ) {
//we're done; clear and dismiss the dialog
clearAndHide();
} else {
//text was invalid
textField.selectAll();
JOptionPane.showMessageDialog(
InputDialogBox.this,
"Please enter a label",
"Try again",
JOptionPane.ERROR_MESSAGE);
typedText = null;
textField.requestFocusInWindow();
}
} else { //user closed dialog or clicked delete
// Delete the object ...
typedText = null;
clearAndHide();
}
}
}
/** This method clears the dialog and hides it. */
public void clearAndHide() {
textField.setText(null);
setVisible(false);
}
I think you're missing the point of the JOptionPane. It comes with the ability to show it's own dialog...
public class TestOptionPane02 {
public static void main(String[] args) {
new TestOptionPane02();
}
public TestOptionPane02() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JTextField textField = new JTextField(10);
String btnString1 = "Save Object";
String btnString2 = "Delete Object";
//Create an array of the text and components to be displayed.
String msgString1 = "Object label:";
Object[] array = {msgString1, textField};
//Create an array specifying the number of dialog buttons
//and their text.
Object[] options = {btnString1, btnString2};
int result = JOptionPane.showOptionDialog(null, array, "", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, "New Object", options, options[0]);
switch (result) {
case 0:
System.out.println("Save me");
break;
case 1:
System.out.println("Delete me");
break;
}
}
});
}
}
To do it manually, you're going to have to do a little more work.
Firstly, you're going to have to listen to the panel's property change events, looking for changes to the JOptionPane.VALUE_PROPERTY and ignoring any value of JOptionPane.UNINITIALIZED_VALUE...
Once you detect the change, you will need to dispose of your dialog.
The you will need extract the value that was selected via the JOptionPane#getValue method, which returns an Object. You will have to interrupt the meaning to that value yourself...
Needless to say, JOptionPane.showXxxDialog methods do all this for you...
Now if you worried about having to go through all the setup of the dialog, I'd write a utility method that either did it completely or took the required parameters...but that's just me
UPDATED
Don't know why I didn't think it sooner...
Instead of passing an array of String as the options parameter, pass an array of JButton. This way you can attach your own listeners.
options - an array of objects indicating the possible choices the user
can make; if the objects are components, they are rendered properly;
non-String objects are rendered using their toString methods; if this
parameter is null, the options are determined by the Look and Feel
For the flexibility you seem to want you should have your class extend JFrame instead of JDialog. Then declare your buttons as JButtons:
JButton saveButton = new JButton("Save"); and add an actionListnener to this button:
saveButton.addActionListener();
either you can put a class name inside the parenthesis of the saveButton, or you can simply pass it the keyword 'this' and declare a method called actionPerformed to encapsulate the code that should execute when the the button is pressed.
See this link for a JButton tutorial with more details:
http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
i'm trying a very simple GUI in java.
i've just created a small GUI with buttons and when we click each button, it opens a website.
So i have have 3 buttons:
button1 = gmail
button2 = google
button3 = yahoo
when i click on button1 sometimes it opens gmail or google or yahoo.
The same problem with other button too.
Why?
Here is my very simple code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Gui extends Frame implements WindowListener,ActionListener {
//TextField text = new TextField(20);
Button a, b, c;
Process p1, p2, p3;
//private int numClicks = 0;
public static void main(String[] args) {
Gui myWindow = new Gui("Miquelon's");
myWindow.setSize(350,100);
myWindow.setVisible(true);
}
public Gui(String title) {
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
a = new Button("Gmail");
b = new Button ("Google");
c = new Button ("Yahooooo");
add(a);
add(b);
add(c);
//add(text);
a.addActionListener(this);
b.addActionListener(this);
c.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
try
{
{
p1 = Runtime.getRuntime().exec("cmd /c start https://mail.google.com");
p2 = Runtime.getRuntime().exec("cmd /c start https://google.com");
p3 = Runtime.getRuntime().exec("cmd /c start https://yahoo.com");
}
}
catch (IOException ex)
{
Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}
Thank you
Your actionPerformed is running all three. You need to use actionPerformed to determine which button was pressed, and then run the corresponding command.
public void actionPerformed(ActionEvent e)
{
String address = "";
if(e.getSource() == a) address = "https://mail.google.com";
else if(e.getSource() == b) address = "https://google.com";
else if(e.getSource() == c) address = "https://yahoo.com";
else return; // not one of the three buttons, get out!
try
{
// only NEED to store the process if you want to do something with it later
// I just let mine dangle :) it works for me!
Runtime.getRuntime().exec("cmd /c start " + address);
}
catch (IOException ex)
{
Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
}
}
You add the same ActionListener to all three buttons. And in the ACtionListener you open yahoo google and gmail. So what else did you expect?
If you don't differ in your actionPerformed method which button was pressed, then this is the correct behaviour.
There are various possibilities to solve this issue... use a ACtionListener for each button (for example anonymoous)
Or use e.getSource() to determine which button was pressed in the actionPerformed method.
For example:
if(e.getSource().equals(a)) {
address = "https://mail.google.com";
}
You don't identify each button in your actionPerformed event.
Every time the event is executed all three commands are executed
One consider naming your a to gmail so it's more descriptive.
a.addActionListener(new ActionListener() {
void actionPerformed(ActionEvent e) {
p1 = Runtime.getRuntime().exec("cmd /c start https://mail.google.com");
}
});
But in short it's running all three.
If you want to do three different things, you either need three different action listeners (one for each button) which each do one thing, or one action listener (one for all buttons) which makes an attempt to determine which button was pressed and does something based on which button called it.
What you have right now is one action listener that does all three things without regard as to which button was pressed.
You could also try setting the ActionCommand for each button so that they can all use the same event listener. This would also improve maintainability if/when you want to add a new button.
a = new Button("Gmail");
a.setActionCommand( "https://gmail.com" );
b = new Button ("Google");
b.setActionCommand( "https://google.com" );
c = new Button ("Yahooooo");
c.setActionCommand( "https://yahoo.com" );
and reimplement your listener method as such:
public void actionPerformed(ActionEvent e)
{
try
{
{
Runtime.getRuntime().exec("cmd /c start " + e.getActionEvent());
}
}
catch (IOException ex)
{
Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm trying to create a button that changes color of the background and then removes itself from the JFrame after a set amount of time, but instead of changing color it just stays pressed for the duration of wait.
public void actionPerformed(ActionEvent e) {
setBackground(Color.red);
try{
Thread.sleep(10000);
}
catch (InterruptedException iE) {
}
frame.remove(this);
}
Can anyone see what im doing wrong?
Your sleep is occurring in the main UI thread, hence the reason the button just stays pressed. If you want a sleep you should create a new thread, get that to sleep, then from within that thread you can get the frame to remove the button.
new Thread() {
public void run() {
try {
Thread.sleep(10000);
// Now do what is needed to remove the button.
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();