In my application I need to get a response between 1 and 9 from the user. I am using a JTextField to get the input. However when a button is pressed the user the JTextField becomes unresponsive. Here is a stripped down example of the problem:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
public class InputTest {
private JTextField inputBox;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new InputTest();
}
});
} // end main()
public InputTest() { // constructor
JFrame f = new JFrame("Input Test");
f.setBounds(100, 100, 450, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
JLabel label = new JLabel("Enter an integer:");
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
label.setBounds(109, 120, 109, 30);
f.add(label);
inputBox = new JTextField();
inputBox.setBounds(259, 120, 30, 30);
f.add(inputBox);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed");
}
});
button.setMnemonic('B');
button.setBounds(166, 198, 78, 23);
f.add(button);
f.setVisible(true);
inputBox.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c < '!' || e.getModifiers() > 0)
return;
if (c < '1' || c > '9') {
JOptionPane.showMessageDialog(null, c
+ " is not an integer");
// inputBox.setText("error");
System.out.println("You typed a non-integer");
} else
System.out.println("You typed " + c);
inputBox.setText(null);
}
});
} // end constructor
} // end class
You should almost never use a KeyListener with a Swing JTextComponent such as a JTextField, for example what happens when the user tries to copy and paste in their input? Instead consider using either a JFormattedTextField, or a JTextField with a DocumentFilter, or my choice -- a JSpinner.
import java.awt.event.ActionEvent;
import javax.swing.*;
public class InputTest2 extends JPanel {
private JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, 9, 1));
private JButton getSelectionButton = new JButton(new GetSelectionAction("Get Selection"));
public InputTest2() {
add(spinner);
add(getSelectionButton);
}
private static void createAndShowGui() {
InputTest2 mainPanel = new InputTest2();
JFrame frame = new JFrame("InputTest2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private class GetSelectionAction extends AbstractAction {
public GetSelectionAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent evt) {
int value = ((Integer)spinner.getValue()).intValue();
System.out.println("You've selected " + value);
}
}
}
Related
So, I have this task where the user guess the correct number just by clicking on the JLabel I have presented for them. What I was trying to is to generate a random number then use if (e.getSource() == random) { } but it seems object and int isn't a compatible operand and I was hoping if someone has any solution to this.
Anyways, here is the source code of what I am doing nothing good since I don't have any solution on my first problem yet.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test123 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test123 window = new Test123();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test123() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Random generator = new Random();
int num;
num = generator.nextInt(9) + 1;
int count = 0;
frame = new JFrame();
frame.setBounds(100, 100, 405, 195);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel NO1 = new JLabel("1");
NO1.setBounds(20, -26, 43, 183);
NO1.setFont(new Font("Arial", Font.BOLD, 75));
frame.getContentPane().add(NO1);
JLabel NO2 = new JLabel("2");
NO2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO2.setFont(new Font("Arial", Font.BOLD, 75));
NO2.setBounds(60, -26, 43, 183);
frame.getContentPane().add(NO2);
JLabel NO3 = new JLabel("3");
NO3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO3.setFont(new Font("Arial", Font.BOLD, 75));
NO3.setBounds(102, -26, 43, 183);
frame.getContentPane().add(NO3);
JLabel NO4 = new JLabel("4");
NO4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO4.setFont(new Font("Arial", Font.BOLD, 75));
NO4.setBounds(143, -26, 43, 183);
frame.getContentPane().add(NO4);
JLabel NO5 = new JLabel("5");
NO5.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO5.setFont(new Font("Arial", Font.BOLD, 75));
NO5.setBounds(184, -26, 43, 183);
frame.getContentPane().add(NO5);
JLabel NO6 = new JLabel("6");
NO6.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO6.setFont(new Font("Arial", Font.BOLD, 75));
NO6.setBounds(223, -26, 43, 183);
frame.getContentPane().add(NO6);
JLabel NO7 = new JLabel("7");
NO7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO7.setFont(new Font("Arial", Font.BOLD, 75));
NO7.setBounds(264, -26, 43, 183);
frame.getContentPane().add(NO7);
JLabel NO8 = new JLabel("8");
NO8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO8.setFont(new Font("Arial", Font.BOLD, 75));
NO8.setBounds(304, -26, 43, 183);
frame.getContentPane().add(NO8);
JLabel NO9 = new JLabel("9");
NO9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO9.setFont(new Font("Arial", Font.BOLD, 75));
NO9.setBounds(345, -26, 43, 183);
frame.getContentPane().add(NO9);
JLabel CorrectAns = new JLabel("Correct!");
CorrectAns.setEnabled(false);
CorrectAns.setBounds(181, 132, 46, 14);
frame.getContentPane().add(CorrectAns);
NO1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == num) {
count++;
CorrectAns.setText("Correct!" + count + " attempts");
}
}
});
}
}
MouseEvent#getSource will return the object which trigged the event, in your case, the JLabel.
A "generally" better solution might be to use JButton instead, then take advantage of the ActionListener. I'd attach a single ActionListener to the "correct" button to handle the correct workflow and a ActionListener to the others to handle the incorrect state
See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Twst {
public static void main(String[] args) {
new Twst();
}
public Twst() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
randomButtons();
}
protected void randomButtons() {
removeAll();
List<JButton> buttons = new ArrayList<>(4);
Random rnd = new Random();
Set<Integer> numbers = new HashSet<>();
while (numbers.size() < 4) {
int number = rnd.nextInt(99) + 1;
numbers.add(number);
}
for (Integer number : numbers) {
JButton btn = new JButton(Integer.toString(number));
add(btn);
buttons.add(btn);
}
Collections.shuffle(buttons);
JButton correct = buttons.remove(0);
correct.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(TestPane.this, "Correct");
randomButtons();
}
});
ActionListener wrong = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JButton) {
JButton btn = (JButton) evt.getSource();
btn.setEnabled(false);
}
JOptionPane.showMessageDialog(TestPane.this, "Wrong");
// You could keep a counter or do what ever else you
// want with a wrong guess
}
};
for (JButton btn : buttons) {
btn.addActionListener(wrong);
}
revalidate();
repaint();
}
}
}
The situation is that the JButton1 corresponds to JLabel1, JButton2 to JLabel2 and so on. However I want to disable the JButton# when the value of Jlabel returns on the TextField and reenable them when it is gone.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.*;
import javax.swing.*;
public class qwerty {
ArrayList<JTextField> tfs = new ArrayList<JTextField>();
ArrayList<JButton> bts = new ArrayList<JButton>();
int counter = 0;
String answer;
JLabel j1 = new JLabel("Mark");
JLabel j2 = new JLabel("Joe");
JLabel j3 = new JLabel("John");
JLabel j4 = new JLabel("Ray");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new qwerty();
}
});
}
public qwerty() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
// Add new buttons to bts
bts.add(new JButton("Button1"));
bts.add(new JButton("Button2"));
bts.add(new JButton("Button3"));
bts.add(new JButton("Button4"));
// Add new textfields to tfs
tfs.add(new JTextField());
tfs.add(new JTextField());
tfs.add(new JTextField());
j1.setPreferredSize(new Dimension(100, 25));
j2.setPreferredSize(new Dimension(100, 25));
j3.setPreferredSize(new Dimension(100, 25));
j4.setPreferredSize(new Dimension(100, 25));
for (JButton b : bts) {
b.addActionListener(new ButtonActionListener());
b.setPreferredSize(new Dimension(100, 25));
frame.getContentPane().add(b);
}
frame.getContentPane().add(j1);
frame.getContentPane().add(j2);
frame.getContentPane().add(j3);
frame.getContentPane().add(j4);
for (JTextField tf : tfs) {
tf.setPreferredSize(new Dimension(100, 25));
tf.setEditable(false);
frame.getContentPane().add(tf);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
public class ButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (counter >= tfs.size()) {
counter = 0;
}
String a = ((AbstractButton) e.getSource()).getText();
if (a == "Button1"){
tfs.get(counter).setText(j1.getText());
}
if (a == "Button2"){
tfs.get(counter).setText(j2.getText());
}
if (a == "Button3"){
tfs.get(counter).setText(j3.getText());
}
if (a == "Button4"){
tfs.get(counter).setText(j4.getText());
}
counter++;
}
}
}
You would use a DocumentListener to monitor the change in the text field and then set the state of the button.
Here is some code that allows you to associate 1 (or more) text fields with a button.
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.*;
public class DataEntered implements DocumentListener
{
private JButton button;
private List<JTextField> textFields = new ArrayList<JTextField>();
public DataEntered(JButton button)
{
this.button = button;
}
public void addTextField(JTextField textField)
{
textFields.add( textField );
textField.getDocument().addDocumentListener( this );
}
public boolean isDataEntered()
{
for (JTextField textField : textFields)
{
if (textField.getText().trim().length() == 0)
return false;
}
return true;
}
#Override
public void insertUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void removeUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void changedUpdate(DocumentEvent e) {}
private void checkData()
{
button.setEnabled( isDataEntered() );
}
private static void createAndShowUI()
{
JButton submit = new JButton( "Submit" );
submit.setEnabled( false );
JTextField textField1 = new JTextField(10);
JTextField textField2 = new JTextField(10);
DataEntered de = new DataEntered( submit );
de.addTextField( textField1 );
de.addTextField( textField2 );
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textField1, BorderLayout.WEST);
frame.add(textField2, BorderLayout.EAST);
frame.add(submit, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Text must be entered in all text field in order to enable the button.
In your case you have a one-to-one mapping of text field to button, so you only need to enter text in one text field in order to enable the related button.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class qwerty implements DocumentListener{
ArrayList<JTextField> tfs = new ArrayList<JTextField>();
ArrayList<JButton> bts = new ArrayList<JButton>();
int counter = 0;
String answer;
JLabel j1 = new JLabel("Mark");
JLabel j2 = new JLabel("Joe");
JLabel j3 = new JLabel("John");
JLabel j4 = new JLabel("Ray");
JButton b1 = new JButton("Button1");
JButton b2 = new JButton("Button2");
JButton b3 = new JButton("Button3");
JButton b4 = new JButton("Button4");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new qwerty();
}
});
}
public qwerty() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
// Add new buttons to bts
bts.add(b1);
bts.add(b2);
bts.add(b3);
bts.add(b4);
Add new textfields to tfs
tfs.add(new JTextField());
tfs.add(new JTextField());
tfs.add(new JTextField());
j1.setPreferredSize(new Dimension(100, 25));
j2.setPreferredSize(new Dimension(100, 25));
j3.setPreferredSize(new Dimension(100, 25));
j4.setPreferredSize(new Dimension(100, 25));
for (JButton b : bts) {
b.addActionListener(new ButtonActionListener());
b.setPreferredSize(new Dimension(100, 25));
frame.getContentPane().add(b);
}
frame.getContentPane().add(j1);
frame.getContentPane().add(j2);
frame.getContentPane().add(j3);
frame.getContentPane().add(j4);
for (JTextField tf : tfs) {
tf.setPreferredSize(new Dimension(100, 25));
tf.setEditable(false);
tf.getDocument().addDocumentListener( this );
frame.getContentPane().add(tf);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
public boolean isDataEntered1()
{
for (JTextField tf : tfs)
{
if ("Mark".equals(tf.getText()))
return false;
}
return true;
}
public boolean isDataEntered2()
{
for (JTextField tf : tfs)
{
if ("Joe".equals(tf.getText()))
return false;
}
return true;
}
public boolean isDataEntered3()
{
for (JTextField tf : tfs)
{
if ("John".equals(tf.getText()))
return false;
}
return true;
}
public boolean isDataEntered4()
{
for (JTextField tf : tfs)
{
if ("Ray".equals(tf.getText()))
return false;
}
return true;
}
#Override
public void insertUpdate(DocumentEvent e) {
checkData();
}
#Override
public void removeUpdate(DocumentEvent e) {
checkData();
}
#Override
public void changedUpdate(DocumentEvent e) {}
private void checkData()
{
b1.setEnabled(isDataEntered1());
b2.setEnabled(isDataEntered2());
b3.setEnabled(isDataEntered3());
b4.setEnabled(isDataEntered4());
}
public class ButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (counter >= tfs.size()) {
counter = 0;
}
String a = ((AbstractButton) e.getSource()).getText();
if (a == "Button1"){
tfs.get(counter).setText(j1.getText());
}
if (a == "Button2"){
tfs.get(counter).setText(j2.getText());
}
if (a == "Button3"){
tfs.get(counter).setText(j3.getText());
}
if (a == "Button4"){
tfs.get(counter).setText(j4.getText());
}
counter++;
}
}
}
In my form, when i press ENTER button in my keyboard, the okAction() method should be invoke (and invoke perfectly).
My problem is in focus state, When i fill the text fields and then press the ENTER button, the okAction() didn't invoked, because the focus is on the second text field (not on the panel).
How fix this problem?
public class T3 extends JFrame implements ActionListener {
JButton cancelBtn, okBtn;
JLabel fNameLbl, lNameLbl, tempBtn;
JTextField fNameTf, lNameTf;
public T3() {
add(createForm(), BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new T3();
}
});
}
public JPanel createForm() {
JPanel panel = new JPanel();
panel.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Button");
panel.getActionMap().put("Button", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
okAction();
}
});
okBtn = new JButton("Ok");
okBtn.addActionListener(this);
cancelBtn = new JButton("Cancel");
tempBtn = new JLabel();
fNameLbl = new JLabel("First Name");
lNameLbl = new JLabel("Last Name");
fNameTf = new JTextField(10);
fNameTf.setName("FnTF");
lNameTf = new JTextField(10);
lNameTf.setName("LnTF");
panel.add(fNameLbl);
panel.add(fNameTf);
panel.add(lNameLbl);
panel.add(lNameTf);
panel.add(okBtn);
panel.add(cancelBtn);
panel.add(tempBtn);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 50, 10, 80, 60);
return panel;
}
private void okAction() {
if (fNameTf.getText().trim().length() != 0 && lNameTf.getText().trim().length() != 0) {
System.out.println("Data saved");
} else System.out.println("invalid data");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okBtn) {
okAction();
}
}
}
Declare a default button for your GUI's JRootPane:
public T3() {
//!! ..... etc...
setVisible(true);
getRootPane().setDefaultButton(okBtn);
}
In fact with a default button set, I don't see that you need to use key bindings.
I have a frame that when i click ok button on tester2 frame, tester1 frame should be seen and when click showbumber button, a random number should be displayed in my label.
But i can't see this generated number while i use sleep method!
Thank for help.
public class tester2 extends JFrame implements ActionListener {
public tester2() {
setTitle("Hello");
setLayout(new FlowLayout());
JButton okButton = new JButton("Ok");
okButton.addActionListener(this);
add(okButton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
tester1 tester1 = new tester1(tester2.this);
tester1.setVisible(true);
}
public static void main(String[] args) {
new tester2().setVisible(true);
}
}
tester 1:
public class tester1 extends JDialog implements ActionListener {
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel(" ");
this.add(showButton);
this.add(lbl1);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showButton) {
GenerateNumber();
tester1.this.dispose();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
try {
Thread.sleep(1000);
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
}
}
If your intention is to close the second frame automatically after a short delay, you should use a javax.swing.Timer instead.
Blocking the EDT will stop it from (amongst other things) processing repaint request, which means your UI can't be updated when you can Thread.sleep
Instead you should use a javax.swing.Timer
public void GenerateNumber() {
Random rnd1 = new Random();
try {
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
timer.setRepeats(false);
timer.start();
}
I don't if your dialog shows the showButton and Label before. Because i have to add a panel in order to show them. After that you need a Timer Class to deal with auto dispose.
Your tester1 look now like this
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class tester1 extends JDialog implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
this.add(jPanel);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel();
jPanel.add(showButton, BorderLayout.NORTH);
jPanel.add(lbl1, BorderLayout.CENTER);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == showButton) {
GenerateNumber();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
lbl1.setText(String.valueOf(rnd1.nextInt(1000000)));
Timer timer = new Timer(1000 * 1, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
timer.setRepeats(false);
timer.start();
}
}
I have a problem, I have been making a Swing application.
My question is about how to handle Jbutton like a JOptionPane, if it's possible?
I want handle all of the buttons similarly to JOptionpane button, but our message written in main function System.out.println("this line executes...how to prevent..");
This function is to display the message, until Jframe is visible.
Can anyone let me know how to prevent & how to handle button functionality? Especially when it executes further when I click the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
JLabel name=new JLabel("Name:");
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(false);
JPanel namePanel = new JPanel();
namePanel.add(name);
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
warningLabel.setForeground(Color.red);
add(warningLabel, BorderLayout.NORTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty :"+name.getText());
warningLabel.setBackground(WARNING_COLOR);
//firstNameField.setText("sorry");
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setSize(200, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGui();
System.out.println("this line executes...how to prevent..");
}
}
Basically, you have something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
System.err.println("Executed once the button has been clicked");
}
}
And you want the line System.err.println("Executed once the button has been clicked"); to be executed when the button is pressed (which is not the case here above).
The solution is actually very simple: you move the code to execute after the button click in another method (see below the proceed() method) and you invoke that line from an ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
proceed();
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
protected void proceed() {
System.err.println("Executed once the button has been clicked");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
}
}
Well, the question is not very much clear,but from your comment,you dont want to do any thing till a JButton is clicked? Or you want to preform a task after clicking of a button?
If that is so, dont put your further code inside your main block, call a function from actionPerformed block.Something like this:
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
display();///////////this is the function containing further code
}
}
//this is display
public void display()
{
System.out.println("this line executes...how to prevent..");
}