Java Determine which textfield has Focus - java

I have created buttons 1-9 as well as 4 text fields. I am trying to allow the user to click on any number 1-9 to input into each text field. However, I cannot determine which field the user is clicked on. Currently the 1-9 buttons only input text to the amt text field. How can I check which field is clicked and enter input into there?
New Question
public void actionPerformed(ActionEvent e) {
String iamt, ii, iterm,ipay;
iamt = amt.getText();
ii = interest.getText();
iterm = term.getText();
ipay = payment.getText();
Is there a way to shorten this if statement so I do not have redundant code for buttons 1-10?
if(e.getSource()==btn1) {
if(previouslyFocusedTextBox.equals(amt)){
amt.setText("1");
amt_number+=amt.getText();
amt.setText(amt_number);
}
else if (previouslyFocusedTextBox.equals(interest)){
interest.setText("1");
int_number+=interest.getText();
interest.setText(int_number);
}
else if (previouslyFocusedTextBox.equals(term)){
term.setText("1");
t_number+=term.getText();
term.setText(t_number);
}
else if (previouslyFocusedTextBox.equals(payment)){
payment.setText("1");
p_number+=payment.getText();
payment.setText(p_number);
}
}
if(e.getSource()==btnPay){
Loan = new LoanforCalc(Double.parseDouble(iamt),Double.parseDouble(ii),Integer.parseInt(iterm));
payment.setText(Double.toString(Loan.getPayment()));
}

I figured out what the OP meant, and made a quick solution:
Essentially, the textboxes lose focus as soon as the button is clicked, so we have to keep track of what had the focus before.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.FileNotFoundException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FocusAwareWindow extends JFrame implements ActionListener, FocusListener {
public static void main(String[] args) throws FileNotFoundException {
FocusAwareWindow c = new FocusAwareWindow();
}
private JTextField textFieldA, textFieldB;
private JButton buttonA, buttonB;
private JTextField previouslyFocusedTextBox = textFieldA;
public FocusAwareWindow(){
super();
this.setLayout(new FlowLayout());
textFieldA = new JTextField();
textFieldA.setText("Field A");
textFieldA.setFocusable(true);
textFieldA.addFocusListener(this);
this.add(textFieldA);
textFieldB = new JTextField();
textFieldB.setText("Field B");
textFieldB.setFocusable(true);
textFieldB.addFocusListener(this);
this.add(textFieldB);
buttonA = new JButton("Which is focused?");
buttonA.addActionListener(this);
this.add(buttonA);
this.pack();
this.setVisible(true);;
}
public void actionPerformed(ActionEvent ev) {
if(previouslyFocusedTextBox.equals(textFieldA)){
System.out.println("Text Field A");
} else if(previouslyFocusedTextBox.equals(textFieldB)){
System.out.println("Text Field B");
}
}
public void focusGained(FocusEvent ev) {
if(ev.getSource() instanceof JTextField) {
previouslyFocusedTextBox = (JTextField) ev.getSource();
}
}
public void focusLost(FocusEvent ev) {
}
}

Maybe add a mouseListener and create areas over the textFields? Just guessing here but it might work. If this is possible then all you need is a variable to keep track of which area you clicked on and then check the variable for the textField you want.

Related

How to check JTextField for an entered number

I’m trying to check the number button that has been pressed in an if statement. I’ve tried to google the question but perhaps I cannot phrase the question well enough.
Here is the code, I read that less code is easier to understand, so I’ve tried to condense my question as much as possible, I hope I haven't condensed it too much.
JButton One = new JButton("1");
One.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.append("1");
}
});
if(textArea.equals("1")){
System.out.println("test");//doesnt print
}
use a variable to store the text:
String theText;
theText = textArea.getText();
then do string comparison:
if(theText.equals("1")) {}
or shorthand:
if(textArea.getText().equals("1")) {}
Also, the if statement should be inside the actionPerformed method otherwise it has already been executed (resulting in FALSE) by the time the button is clicked. Use textArea.append() if you want to append a new "1" to each previous "1" in the text area every time the button is clicked, otherwise use textArea.setText() to just continually overwrite the previous "1" that was set from any previous button click. A working example can be seen here:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class Tester {
public static void main(String args[]) {
JButton aButton = new JButton("Button");
JPanel aPanel = new JPanel();
JTextArea aTextArea = new JTextArea();
JFrame aFrame = new JFrame();
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setSize(200, 200);
aPanel.add(aTextArea);
aPanel.add(aButton);
aFrame.add(aPanel);
aFrame.setVisible(true);
aButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
aTextArea.setText("1");
if(aTextArea.getText().equals("1")) {
System.out.println("Test Works");
}
}});
}
}
UPDATE:
If you would like to not only check the contents of the text area when the button is pressed, but whenever text is entered. Kind of the same "idea" to your if-statement being outside of the button action listener. You need to use either a FocusListener or a KeyListener on the text area. A focus listener will execute when you either click in, or click out of the text area. A key listener will execute on various types of key press/release etc. I think what you are looking for is a KeyListener based on your comments. I've provided an example of each, that works with my previous example:
/*
This is probably not the one you want
*/
aTextArea.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
if(aTextArea.getText().equals("1")) {
System.out.println("Test Worls");
}
}});
/*
With this KeyListener
The second someone types "1" in the text area
It compares the strings, and the test works
*/
aTextArea.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
String currentText = aTextArea.getText();
if(currentText.equals("1")) {
JOptionPane.showMessageDialog(null, "Test Works");
}
}
public void keyPressed(KeyEvent e) {
}
});
Try inserting the above code in the example I had previously provided. Remember to comment out the button ActionListener and to import the following:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

FocusListener & JOptionPane

There is the code of my simple Program.
There are four textFields.
when cursor is on first textField JOptionPane is Created and when I press ok
cursor moves to next field and OptionPane is created again
and so on
when cursor is on fourth field and I click OK on OptionPane,cursor moves to fifth field "f".
when cursor is in field,I print the possition of the field in array: System.out.println("first or Second or Third or Fourth")
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Hello extends JFrame implements ActionListener, FocusListener {
public JTextField[] fields = new JTextField[4];
public JPanel panel = new JPanel();
public JTextField f = new JTextField(12);
public static void main(String[] args) {
new Hello();
}
public Hello() {
for (int i = 0; i < 4; i++) {
fields[i] = new JTextField(12);
fields[i].addFocusListener(this);
panel.add(fields[i]);
}
add(panel);
add(f);
setTitle("Hello World");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(920, 420);
setLocation(100, 100);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
}
#Override
public void focusGained(FocusEvent fe) {
if (fe.getSource() == fields[0]) {
JOptionPane.showMessageDialog(null, "HELLO");
fields[1].requestFocus();
System.out.println("FIRST");
} else if (fe.getSource() == fields[1]) {
JOptionPane.showMessageDialog(null, "HELLO");
fields[2].requestFocus();
System.out.println("SECOND");
} else if (fe.getSource() == fields[2]) {
JOptionPane.showMessageDialog(null, "HELLO");
fields[3].requestFocus();
System.out.println("THIRD");
} else if (fe.getSource() == fields[3]) {
JOptionPane.showMessageDialog(null, "HELLO");
f.requestFocus();
System.out.println("FOURTH")
}
}
#Override
public void focusLost(FocusEvent fe) {
}
}
When there is no OptionPane,the cursor moves forward from first field to the fourth and prints:
FIRST
SECOND
THIRD
FOURTH
but when there is JOptionPane
the output is :
FIRST
SECOND
FIRST
SECOND
THIRD
SECOND
THIRD
FOURTH
THIRD
FOURTH
FOURTH
One can see that after second field it comes back to first,
after third field it comes back to second,instead of to go to fourth
after fourth field it comes back to third.
I want to know why? and how can I fix this
The problem is that every time you click OK on the JOptionPane, the focus is returned to the last JTextField active before the JOptionPane was shown, so a new requestFocus event is added to the event queue for that control. Actually after the first time you click OK while executing your code, several dialogs are fire, you just don't see it because you show the same text (HELLO) every time. I have changed your code to make it work. Hope it helps!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class testOptionPane extends JFrame implements ActionListener, FocusListener {
public ArrayList<JTextField> fields = new ArrayList<>();
public JPanel panel = new JPanel();
public JTextField f = new JTextField(12);
private int currentField = 0;
private boolean focusReturned = false;
public static void main(String[] args) {
new testOptionPane();
}
public testOptionPane() {
for (int i = 0; i < 4; i++) {
JTextField tf = new JTextField(12);
fields.add(tf);
tf.addFocusListener(this);
panel.add(tf);
}
add(panel);
fields.add(f);
add(f);
setTitle("Hello World");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(920, 420);
setLocation(100, 100);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
}
#Override
public void focusGained(FocusEvent fe) {
if (fe.getSource() == fields.get(currentField)) {
if (!focusReturned) {
JOptionPane.showMessageDialog(this, "focus on field " + String.valueOf(currentField));
System.out.println(currentField);
focusReturned = true;
} else {
currentField++;
focusReturned = false;
if (currentField < fields.size()) {
fields.get(currentField).requestFocus();
}
}
}
}
#Override
public void focusLost(FocusEvent fe) {
}
}

Selecting / highlighting text in a JTextArea belonging to a JOptionPane

My problem is the following: In my application the user clicks a button which brings up a dialog box (a custom jOptionPane). This dialog contains a JTextArea in which the user will type a response, which will then be processed by the application, however I would like this JTextArea (which will hold the user's input and currently contains example text like "Write your answer here") to be automatically highlighted.
I can do this normally, by calling requestFocusInWindow() followed by selectAll() on the JTextArea however there seems to be a problem when this is done using a JOptionPane which I'm guessing is to do with the fact that the focus cannot shift to the JTextArea successfully.
I've made a SSCCE to demonstrate this clearly, and hopefully get an answer from one of you guys as to how I can make this possible. Thanks in advance!
Class 1/2 : Main
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main extends JFrame{
public static void main(String[] args) {
Main main = new Main();
main.go();
}
private void go() {
JPanel background = new JPanel();
JPanel mainPanel = new ExtraPanel();
((ExtraPanel) mainPanel).setupPanel();
JButton testButton = new JButton("Test the jOptionPane");
testButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
optionPaneTest();
}
});
background.add(mainPanel);
background.add(testButton);
getContentPane().add(background);
pack();
setVisible(true);
}
private void optionPaneTest() {
JPanel testPanel = new ExtraPanel();
((ExtraPanel) testPanel).setupPanel();
int result = JOptionPane.showConfirmDialog(null, testPanel,
"This is a test", JOptionPane.OK_CANCEL_OPTION);
}
}
----------------------------------------------------------------------------- Class 2/2 : ExtraPanel
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ExtraPanel extends JPanel{
public void setupPanel() {
JTextArea textArea = new JTextArea();
textArea.setText("Write your response here");
textArea.requestFocusInWindow();
textArea.selectAll();
add(textArea);
}
}
Just add
textArea.getCaret().setSelectionVisible(true)
After textArea.selectAll();
If you want focus in the TextArea so that the user can immediately start typing, you can trigger the selection using the ancestor added event.
public void setupPanel() {
final JTextArea textArea = new JTextArea();
textArea.setText("Write your response here");
textArea.addAncestorListener(new AncestorListener() {
public void ancestorRemoved(AncestorEvent event) { }
public void ancestorMoved(AncestorEvent event) { }
public void ancestorAdded(AncestorEvent event) {
if (event.getSource() == textArea) {
textArea.selectAll();
textArea.requestFocusInWindow();
}
}
});
add(textArea);
}

Making a JTextField with Vanishing Text

I am familiar that you can input text before hand into a JTextField. This text will be displayed in the JTextField and has to be manually deleted when having to input your own text into the JTextField. For example, consider this JTextField:
cruiseSel = new JTextField ("Selected Cruise:");
cruiseSel.setEditable(false);
centerP12.add(cruiseSel);
contentPane12.add(centerP12, BorderLayout.CENTER);
Frame12.setVisible(true);
Upon running the above, a JTextField will appear with "Selected Cruise:" written within it. This text then has to be manually deleted to clear the text field.
Is there a way to input text in an JTextField, so once the GUI opens, the text will be displayed, but when the JTextField is selected to input manual text, the text vanishes?
You could use a FocusListener and when the JTextField receives focus, empty the text.
Of course you will want a state marker to indicate it has the default text and not do this once you have user entered text. Either that or after the FocusListener is hit the first time, remove it.
textField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
JTextField source = (JTextField)e.getComponent();
source.setText("");
source.removeFocusListener(this);
}
});
What you are looking for is called placeholder. I've written this class a while ago:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
/**
* #author xehpuk
*/
public class PlaceholderTextField extends JTextField {
private static final long serialVersionUID = -5529071085971698388L;
/**
* The placeholder to be displayed if the text field is empty.
*/
private String placeholder;
/**
* Determines whether the placeholder should be displayed even on focus.
*/
private boolean paintingOnFocus;
/**
* The color the placeholder should be displayed in.
*/
private Color placeholderColor;
public String getPlaceholder() {
return placeholder;
}
public void setPlaceholder(final String placeholder) {
this.placeholder = placeholder;
repaint();
}
public boolean isPaintingOnFocus() {
return paintingOnFocus;
}
public void setPaintingOnFocus(final boolean paintingOnFocus) {
this.paintingOnFocus = paintingOnFocus;
repaint();
}
public Color getPlaceholderColor() {
return placeholderColor;
}
public void setPlaceholderColor(final Color placeholderColor) {
this.placeholderColor = placeholderColor;
repaint();
}
public PlaceholderTextField() {
super();
}
public PlaceholderTextField(final Document doc, final String text, final int columns) {
super(doc, text, columns);
}
public PlaceholderTextField(final int columns) {
super(columns);
}
public PlaceholderTextField(final String text, final int columns) {
super(text, columns);
}
public PlaceholderTextField(final String text) {
super(text);
}
{
addFocusListener(new RepaintFocusListener());
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
if (getPlaceholder() != null && getText().isEmpty() && (isPaintingOnFocus() || !isFocusOwner())) {
try {
final Rectangle rect = getUI().modelToView(this, 0);
final Insets insets = getInsets();
g.setFont(getFont());
g.setColor(getPlaceholderColor() == null ? getForeground() : getPlaceholderColor());
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawString(getPlaceholder(), rect.x, getHeight() - insets.top - insets.bottom - rect.y);
} catch (final BadLocationException e) {
throw new RuntimeException(e);
}
}
}
private class RepaintFocusListener implements FocusListener {
#Override
public void focusGained(final FocusEvent e) {
repaint();
}
#Override
public void focusLost(final FocusEvent e) {
repaint();
}
}
}
You can choose the text and the color and whether it should be painted even if the text field has focus.
The crucial part is the overriding of paintComponent(Graphics).
You can use SwingX Read on this How to set Text like Placeholder in JTextfield in swing
I include the sample code here for your use
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.prompt.PromptSupport;
public class PromptExample {
public static void main(String[] args) {
new PromptExample();
}
public PromptExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField bunnies = new JTextField(10);
JTextField ponnies = new JTextField(10);
JTextField unicorns = new JTextField(10);
JTextField fairies = new JTextField(10);
PromptSupport.setPrompt("Bunnies", bunnies);
PromptSupport.setPrompt("Ponnies", ponnies);
PromptSupport.setPrompt("Unicorns", unicorns);
PromptSupport.setPrompt("Fairies", fairies);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, bunnies);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIGHLIGHT_PROMPT, ponnies);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, unicorns);
PromptSupport.setFontStyle(Font.BOLD, bunnies);
PromptSupport.setFontStyle(Font.ITALIC, ponnies);
PromptSupport.setFontStyle(Font.ITALIC | Font.BOLD, unicorns);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(bunnies, gbc);
frame.add(ponnies, gbc);
frame.add(unicorns, gbc);
frame.add(fairies, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Check out Text Prompt.
It supports this functionality along with a couple of features to customize the behaviour of the prompt.
To achieve something like this, you would generally need to create a certain type of event listener. In your case, the desired action needs to be triggered on a mouse event - thus the MouseAdapter event listener seems like a good fit (at first glance). To use the MouseAdapter
abstract class, you'd need to extend it and override the necessary methods (see here for a full list of available methods).
The shortest way of achieving this is via an anonymous class declaration, like so:
cruiseSel.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
cruiseSel.setText("");
}
});
(However, if you need to override multiple methods or the triggered logic feels complex enough, you might be better off creating a separate listener class.)
EDIT: Alternatively, as #HovercraftFullOfEels pointed out in the comment section, it would probably be wiser to apply the FocusAdapter class (see here) in an identical fashion:
cruiseSel.addFocusListener(new FocusAdapter(){
#Override
public void focusGained(FocusEvent e){
cruiseSel.setText("");
}
});
The problem with the first solution is that it is only concerned with listening for actual MOUSE CLICKS on the text field, while the latter listens for ANY types of focus-gains on it. Thus, when using the TAB key to switch between text fields, only the second solution would perform correctly.

Needing to return value from user input

a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)

Categories

Resources