Checking if a JTextfield is selected or not - java

Is it possible to check if a jtextfield has been selected / de-selected (ie the text field has been clicked and the cursor is now inside the field)?
//EDIT
thanks to the help below here is a working example
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class test extends JFrame {
private static JPanel panel = new JPanel();
private static JTextField textField = new JTextField(20);
private static JTextField textField2 = new JTextField(20);
public test() {
panel.add(textField);
panel.add(textField2);
this.add(panel);
}
public static void main(String args[]) {
test frame = new test();
frame.setVisible(true);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
System.out.println("selected");
}
#Override
public void focusLost(FocusEvent e) {
System.out.println("de-selected");
}
});
}
}

You will need to use the focusGained and focusLost events to see when it has been selected, and when it is deselected (i.e. gained/lost focus).
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class Main {
public static void main(String args[]) {
final JTextField textField = new JTextField();
textField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
//Your code here
}
#Override
public void focusLost(FocusEvent e) {
//Your code here
}
});
}
}

You may try isFocusOwner()

Is it possible to check if a jtextfield has been selected / de-selected
Yes, use focusGained and focusLost events.
the text field has been clicked and the cursor is now inside the field ?
Use isFocusOwner() which returns true if this Component is the focus owner.

if( ((JFrame)getTopLevelAncestor()).getFocusOwner() == textField ) {
....
}

Related

How to Connect the Button and a Text Area from different Classes in Java

I want to make a window that when you press the buttons it will show the phrase "I Love You" in different language in the text area. I Just don't know how to connect the text area in the buttons. I have three classes. I tried many ways I could think and I also search the things related to this but I can't find any useful
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainClass {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
private ToolBar Tulbar = new ToolBar();
private JTextArea textArea = new JTextArea();
public MainFrame() {
super("This window loves you");
setLayout(new BorderLayout());
add(Tulbar, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ToolBar extends JPanel{
private JButton Button1 = new JButton("Korean");
private JButton Button2 = new JButton("Japanese");
private JButton Button3 = new JButton("French");
private JButton Button4 = new JButton("Italian");
private JButton Button5 = new JButton("English");
private JButton Button6 = new JButton("Tagalog");
public ToolBar() {
setLayout(new FlowLayout(FlowLayout.LEFT));
//added buttons
add(Button1);
add(Button2);
add(Button3);
add(Button4);
add(Button5);
add(Button6);
}
public ToolBar(JTextArea frame) {
Button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Saranghae");
}
});
Button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Aishiteru");
}
});
Button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Je t\'aime");
}
});
Button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Ti\'amo");
}
});
Button5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("I Love You");
}
});
Button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.append("Mahal Kita");
}
});
}
}
Since you are calling Button1.addActionListener in public ToolBar(JTextArea frame) constructor, you should invoke this constructor to invoke the code in it. But instead you are invoking public ToolBar() constructor.
To fix this instead of:
private ToolBar Tulbar = new ToolBar();
private JTextArea textArea = new JTextArea();
you should write:
private JTextArea textArea = new JTextArea();
private ToolBar Tulbar = new ToolBar(textArea);
and in ToolBar fix the constructors, instead of:
public ToolBar() {
// ... STUFF 1 ...
}
public ToolBar(JTextArea frame) {
// ... STUFF 2 ...
}
you should write:
public ToolBar(JTextArea frame) {
// ... STUFF 1 ...
// ... STUFF 2 ...
}
or
public ToolBar() {
// ... STUFF 1 ...
}
public ToolBar(JTextArea frame) {
this();
// ... STUFF 2 ...
}
Please learn Java Naming Conventions and use it all the time. You probably don't think it's important, but I promise it will save you from making stupid mistakes, and will save your time fixing them.

How can I add text to combobox from textfield?

I want to create a combobox and a textbox. And user will enter a text into the textbox, and the text will be added as an item of combobox.
How can I do it? I wrote a code, but I couldn't find what will I write in actionlistener.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox = new JComboBox();
public Q2() {
t = new JTextField("Enter text here", 20);
t.setEditable(true);
t.addActionListener(new act());
add(t);
add(combobox);
combobox.addItem(t.getText().toString());
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}
I added a button, and put the functionality on adding to the JComboBox on the button. Here's an example:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox;
JButton b;
public Q2() {
combobox = new JComboBox();
t = new JTextField("Enter text here", 20);
t.setEditable(true);
b = new JButton("Add");
b.addActionListener(new act()); //Add ActionListener to button instead.
add(t);
add(combobox);
add(b);
//combobox.addItem(t.getText().toString()); //Moved to ActionListener.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
combobox.addItem(t.getText()); //Removed .toString() because it returns a string.
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}
private JTextComponent comboboxEditor;
Vector ComboData = new Vector();
public void addActionListners() {
//adding action listner to the NameComboBox
this.comboboxEditor = (JTextComponent) yourCombo.getEditor().getEditorComponent();
comboboxEditor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
int i = evt.getKeyCode();
if (i == 10) {
//combobox action on enter
ComboData.add(comboboxEditor.getText());
yourCombo.setListData(ComboData);
}
}
});
}
you have to set your editable property in comboBox to true otherwise you wont able to write on comboBox. make sure you call addActionListners() method
at the startup(constructor). i am giving the combobox the functionality of a jtext field by changing the editor of the combobox to jtextComponent. try this example

How to use a JComboBox to add a JTextField

I need to know how to add a JTextField if one of the JComboBox options is selected, and if the other one is selected I don't want to have that text field there any more.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame{
//Not sure if this code is correct
private JTextField text;
private JComboBox box;
private static String[] selector = {"Option 1", "Option 2"};
public GUI(){
super("Title");
setLayout(new FlowLayout());
box = new JComboBox(selector);
add(box);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(){
//what should be in the if statement and what should i type down here to add the
//JTextField to the JFrame?
}
}
}
);
}
}
Try next example, that should help you:
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFrame extends JFrame {
public TestFrame(){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
});
}
private void init() {
final JComboBox<String> box = new JComboBox<String>(new String[]{"1","2"});
final JTextField f = new JTextField(5);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
f.setVisible("1".equals(box.getSelectedItem()));
TestFrame.this.revalidate();
TestFrame.this.repaint();
}
}
});
add(box,BorderLayout.SOUTH);
add(f,BorderLayout.NORTH);
}
public static void main(String... s){
new TestFrame();
}
}

Java JDialogs How To Pass Information Between?

after looking for an answer for 3 hours, I am just about to give up on this idea:
I am making an application that displays the followers of a Twitch streamer.
A couple of features i am trying to add:
the display frame is a separate window from the controls frame.
I am trying to use (JFrame as display window) (JDialog as controls frame)
And furthermore: Settings is in another JDialog (this one has Modal(true))
Settings needs to be able to send the JFrame information such as: "username" and "text color"
And the settings JDialog will only pop up from clicking "settings" on the controls JDialog.
It will setVisible(false) when you click "save settings" or the X.
On the controls JDialog (b_console) needs to receive error messages and info like that.
And on the same JDialog, "filler" needs to receive follower count and things like that.
Here follows my code involving the transfers listed above:
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
public class JavaFollowerNotifier extends JFrame implements ComponentListener
{
Settings settings = new Settings();
ControlPanel ctrlPnl = new ControlPanel();
public JavaFollowerNotifier()
{
try
{
settings.readSettings();
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabFollower()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabStats()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.filler.setText("Followers: " + totalFollowers + "\nLatest: " + lastFollower);
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void componentMoved(ComponentEvent arg0)
{
//this is only to *attach this JDialog to the JFrame and make it move together my plan is to have it undecorated as well
int x = this.getX() + this.getWidth();
int y = this.getY();
ctrlPnl.movePanel(x, y);
}
public void paint(Graphics g)
{
if(clearPaint == false)
{
//any "savedSettings[n]" are saved in Settings.java (just not in this version)
g.setColor(Color.decode(savedSettings[3]));
scaledFont = scaleFont(follower + " followed!", bounds, g, new Font(savedSettings[2], Font.PLAIN, 200));
}
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Settings extends JDialog implements ActionListener
{
JavaFollowerNotifier jfollow = new JavaFollowerNotifier();
ControlPanel ctrlPnl = new ControlPanel();
//here are the settings mention above
String[] savedSettings = {"imgs/b_b.jpg","username","font","color","Nightbot"};
public Settings()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void saveSettings()
{
savedSettings[4] = jfollow.lastFollower;
try
{
PrintWriter save = new PrintWriter("config.cfg");
ctrlPnl.b_console.setText("Saving...");
for(int i = 0; i < 5; i++)
{
save.println(savedSettings[i]);
}
save.close();
ctrlPnl.b_console.setText("Saved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
canClose = false;
}
readSettings();
this.repaint();
}
public void readSettings()
{
ctrlPnl.b_console.setText("Loading...");
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
jfollow.lastFollower = savedSettings[4];
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
ctrlPnl.b_console.setText("Loaded Settings");
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JDialog implements ActionListener
{
public ControlPanel()
{
try
{
}
catch (Exception e)
{
b_console.setText("Error");
System.out.println(e);
}
}
public void movePanel(int x, int y)
{
//here is where i *attach the JDialog to the JFrame
controlPanel.setLocation(x, y);
}
public void actionPerformed(ActionEvent ie)
{
if(ie.getSource() == b_settings)
{
settings.frame.setVisible(true);
}
}
}
I tried to fix your program, but I wasn't too sure about its flow. So I created another simple one. What I did was pass the labels from the main frame to the dialogs' constructors. In the dialog, I took those labels and changed them with text entered in their text fields. If you hit enter after writing text from the dialog, you'll see the text in the frame change
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
....
class ControlDialog extends JDialog {
private JLabel label;
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
....
class SettingsDialog extends JDialog {
private JLabel label;
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
Test it out and let me know if you have any questions
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private JButton showControl = new JButton("Show Control");
private JButton showSetting = new JButton("Show Settings");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
showControl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
control.setVisible(true);
}
});
showSetting.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
settings.setVisible(true);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(showControl);
buttonPanel.add(showSetting);
add(buttonPanel, BorderLayout.SOUTH);
add(controlDialogLabel, BorderLayout.NORTH);
add(settingDialogLabel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JavaFollowerNotifier1();
}
});
}
}
class ControlDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Control Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
ControlDialog.this.setVisible(false);
}
});
}
}
class SettingsDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Settings Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
SettingsDialog.this.setVisible(false);
}
});
}
}
Typically when I build GUI's which use modal dialogs to gather user input, I build my own class, which extends the JDialog or in some cases a JFrame. In that class I expose a getter method for an object which I usually call DialgResult. This object acts as the Model for the input I gather from the user. In the class that has the button, or whatever control which triggers asking the user for the information, I create it, show it as a modal dialog, then when it is closed, I retrieve the object using that same getter.
This is a very primitive example:
package arg;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class asdfas extends JFrame {
public static void main(String[] args) {
asdfas ex = new asdfas();
ex.setVisible(true);
}
public asdfas() {
init();
}
private void init() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
final JButton button = new JButton("Show modal dialog");
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Dialog d = new Dialog();
d.setVisible(true);
button.setText(d.getDialogResult().value);
revalidate();
repaint();
}
});
this.add(button);
}
class DialogResult {
public String value;
}
class Dialog extends JDialog {
JTextField tf = new JTextField(20);
private DialogResult result = new DialogResult();
public Dialog() {
super();
init();
}
private void init() {
this.setModal(true);
this.setSize(new Dimension(100,100));
JButton ok = new JButton("ok");
ok.addActionListener( new ActionListener () {
#Override
public void actionPerformed(ActionEvent arg0) {
result = new DialogResult();
result.value = tf.getText();
setVisible(false);
}
});
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(tf);
p.add(ok);
this.add(p);
}
public DialogResult getDialogResult() {
return result;
}
}
}

Java - Change JLabel

I have a class of buttons called Keys.java which returns a panel of buttons to the class called Control.java. I have a JLabel in Control.java, but what I want to do is change a JLabel when a button is pressed. How would you go about doing this?
I have tried setting a string in Keys.java which changes based on the button and then setting the JLabel's text equal to the string but it doesn't seem to work.
Any thoughts on how to achieve this?
It may be that you are updating the wrong string or setting the corresponding label's text incorrectly. Both are required. In the example below (using your names), the two updates are tightly coupled in the button's actionPerformed(). A more loosely coupled approach is shown here.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/questions/9053824 */
public class JavaGUI extends JPanel {
private Control control = new Control();
private Keys keys = new Keys("Original starting value.");
public JavaGUI() {
this.setLayout(new GridLayout(0, 1));
this.add(keys);
this.add(control);
}
private class Control extends JPanel {
public Control() {
this.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Command: " + e.getActionCommand());
keys.string = String.valueOf(System.nanoTime());
keys.label.setText(keys.string);
}
}));
}
}
private class Keys extends JPanel {
private String string;
private JLabel label = new JLabel();
public Keys(String s) {
this.string = s;
label.setText(s);
this.add(label);
}
}
private void display() {
JFrame f = new JFrame("JavaGUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JavaGUI().display();
}
});
}
}

Categories