Total re-edit with compilable example that clarifies my issue.
Overall program: Class MainFrame displays a JTable with results from a SQL query. MainFrame also has JButtons for refreshing, adding, updating, and querying the table. Clicking the Update button makes visible a text area and submit button. Users can enter an id number into the text area. When they click submit a new frame, UpdateFrame, opens with all the data from the record the corresponds to the id number.
Stripped-down versions of MainFrame and UpdateFrame are below.
UpdateFrame2.java
package kft1task4;
import javax.swing.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.JScrollPane;
public class UpdateFrame2 extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JTextArea jta = new JTextArea("This is a text area");
UpdateFrame2() {
setVisible(true);
setBounds(1000,400,1000,500);
pane.setLayout(null);
add(pane);
jta.setBounds(110,100,100,15);
pane.add(jta);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
} //End actionListener
} //End class
Very simple. One frame with one panel with one JTextArea. The JTextArea should be editable; I should be able to type in it.
MainFrame2.java
package kft1task4;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
public class MainFrame2 extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton closeButt = new JButton("Push me to close the program");
JButton updateButt = new JButton("Push me to update a record");
JButton submitUpdButt = new JButton("Submit");
JLabel updateLabel = new JLabel("Select student id to update");
JTextArea updateTA = new JTextArea();
MainFrame2(){
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(1000,200,1500,1000);
pane.setLayout(null);
add(pane);
updateButt.setBounds(620,550,200,100);
updateButt.addActionListener(this);
pane.add(updateButt);
closeButt.setBounds(1290,550,200,100);
closeButt.addActionListener(this);
pane.add(closeButt);
submitUpdButt.setBounds(820,735,200,25);
submitUpdButt.addActionListener(this);
submitUpdButt.setVisible(false);
pane.add(submitUpdButt);
updateLabel.setBounds(620,700,200,15);
updateLabel.setVisible(false);
pane.add(updateLabel);
updateTA.setBounds(820,700,200,15);
updateTA.setVisible(false);
pane.add(updateTA);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == closeButt){
System.exit(0);
}
if(source == updateButt){
updateLabel.setVisible(true);
updateTA.setVisible(true);
submitUpdButt.setVisible(true);
}
if(source == submitUpdButt){
//submitUpdButt.setVisible(false);
new UpdateFrame2();
updateTA.setText(null);
updateTA.setVisible(false);
updateLabel.setVisible(false);
submitUpdButt.setVisible(false);
}
}
}
Note the three fields: updateLabel, updateTA, and submitUpdButt (and please forgive the poor naming). When new MainFrame2() is first instantiated, those three fields are .setVisible(False). Clicking updateButt makes them visible.
Click submitUpdButt performs five actions: First, it instantiates a new UpdateFrame2(). Second, it clears the text from UpdateTA. Finally, it makes the three fields invisible. Those 5 actions complete with no problem.
Now here's the oddity: Notice that I've listed "submitUpdButt.setVisible(false)" twice. Once before "new UpdateFrame2()" and once after. I comment out one and leave other in place. If "submitUpdButt.setVisible(false)" appears before "new UpdateFrame2()," the UpdateFrame appears, and its text area is editable.
If "submitUpdButt.setVisible(false)" appears after "new UpdateFrame2()," as it's written above, the UpdateFrame appears. But its text area is not editable.
To clarify: Every other element of the program behaves exactly the same. The 3 fields appear and disappear as expected. The window open and close correctly. The text "This is a text area" appears where it should. No errors are produced. But the text area in UpdateFrame2 is editable or not based on where I put "submitUpdButt.setVisible(false)".
I hope this description is more clear than my last one.
Related
I have a Java Swing application where some data are presented in editable combo boxes. The combo boxes are displayed in a separate frame. The frame is opened ad hoc when a button is clicked. The frame has no window decoration and is closed/disposed when it loses its focus (i.e., the user clicks outside the window). When the frame is closed, the combo box contents are saved.
This works well, except for the last edited combo box. For the last combo box, the contents are still being edited when the window loses focus. The #getSelectedItem() method of the JComboBox returns null because the editing was not completed before the window lost focus. At least I assume that is what is happening.
How can I finish the editing and select the edited text when the window loses focus before disposing the frame?
Here is a minimal reproducible example:
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
class Example extends JFrame {
public static void main(String[] args) {
new Example();
}
public Example() {
Container c = getContentPane();
JPanel panel = new JPanel();
JComboBox<String> box1 = new JComboBox<String>();
box1.setEditable(true);
panel.add(box1);
JComboBox<String> box2 = new JComboBox<String>();
box2.setEditable(true);
panel.add(box2);
c.add(panel);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.addWindowFocusListener(new WindowAdapter() {
public void windowLostFocus(WindowEvent e) {
System.out.println("Field 1: " + box1.getSelectedItem() + ". Field 2: " + box2.getSelectedItem() + ".");
System.exit(0);
}
});
}
}
The example class will display a frame with two editable combo boxes. If you click outside of the frame, the application will exit after printing the contents of the two combo boxes. You will notice that the last edited combo box prints null if it was visited only once.
Add a FocusListener to the combo box text field that is used as the editor. An event should be generated when the text field loses focus.
See the getEditor() method of the JComboBox for access to the editor component.
I am a fairly new user with programming in Java with about a week and a bit experience, as of before I have been using python for about 3 years but thought to give java a try.
I have been trying to develop my skills by creating small projects and applications and am now creating a small GUI counter.
I have achieved creating the GUI with 2 buttons and a label and have tested the maths behind the application but I am struggling to work out how the ActionListener works as it feels a lot different to python when making a button have a action.
This is My Code;
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.*;
public class GUI{
//This creates a frame or panel to contain things
public static void main(String[] args) {
//Maths To The Counter
int Counter = 0;
System.out.println(Counter);
Counter =+ 1;
System.out.println(Counter);
//Creating The Frame
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
//Creating The Label
JLabel label3 = new JLabel("Counter: ");
panel.add(label3);
//Button Which should have a funtion to add and display the number
JButton button = new JButton("Click Here.");
panel.add(button);
//Button to reset the counter
JButton buttonReset = new JButton("Reset Counter.");
panel.add(buttonReset);
//Set Size Of Window
frame.setSize(new Dimension(500, 400));
//Set Starting Position to centre
frame.setLocationRelativeTo(null);
//Setting a default close action
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set Title
frame.setTitle("Counter");
//Disable Resize
frame.setResizable(false);
//Setting if its visible
frame.setVisible(true);
//Fits frame to fit everything
frame.pack();
}
}
enter code here
I know that in python a action is in a function so that has been my logic to this problem however I have seen that I need to use the actionlistener instead and I am struggling to get my head around it.
If Someone could show me how this type of action should be implemented it would be great help, I have watch some youtube videos and done a bit of research but im still struggling to understand in my situation how to do it.
For any confussion im sorry, overall my question is how do I add a action to a button in my program that can implement my maths at the start.
As well any feedback on the structure of my code would be welcomed as I am just starting in java and I do know poor structure can lead to mistakes.
This code should work:
Basically, in the main method I am creating an instance of the class and calling a method to create the gui.
I also created an instance variable as the counter, otherwise you won't be able to update the variable in your action listener.
public class Gui {
private int counter;
// This creates a frame or panel to contain things
public static void main(String[] args) {
Gui gui = new Gui();
gui.create();
}
private void create() {
// Creating The Frame
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
// Creating The Label
JLabel label3 = new JLabel("Counter: ");
panel.add(label3);
// Button Which should have a funtion to add and display the number
JButton button = new JButton("Click Here.");
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(counter++);
}
});
// Button to reset the counter
JButton buttonReset = new JButton("Reset Counter.");
panel.add(buttonReset);
buttonReset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter = 0;
}
});
// Set Size Of Window
frame.setSize(new Dimension(500, 400));
// Set Starting Position to centre
frame.setLocationRelativeTo(null);
// Setting a default close action
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set Title
frame.setTitle("Counter");
// Disable Resize
frame.setResizable(false);
// Setting if its visible
frame.setVisible(true);
// Fits frame to fit everything
}
}
With Lambda expressions, you can simplify your action listeners as follows:
button.addActionListener(a -> System.out.println(counter++));
buttonReset.addActionListener(a -> counter = 0);
If you want to write more than 1 statement, then you can just put your code in curly brackets:
button.addActionListener(a -> {
System.out.println(counter++);
System.out.println("doing more stuff...");
});
JButton has a function called addActionListener. You can pass on an action listener by doing this:
button.addActionListener(() -> {
// Do some logic here
});
Here, I use a lambda expression as an action listener. Within the lambda expression you can place whatever logic you want to have.
Also note that you can add multiple different action listeners to the same button. In a nutshell, the way the JButton interacts with the ActionListeners is based on the observer-pattern.
Imagine this: When the JButton is pressed, it will notify all of it's observers saying "Hey, I have been pressed". Each observer can then independently decide what to do. In case of the JButton, all observers are ActionListeners. If you add multiple ActionListeners then the JButton will notify all of them, and as a result all of their actionPerformed(ActionEvent e) functions are executed. In the example above, I used a lambda expression which then by java is interpreted as an ActionListener.
Other ways to achieve the exact same functionality are:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do some logic here
}
});
In the example above, you use an anonymous class as an actionlistener.
public class MyClass {
public MyClass() {
JButton button = new JButton("press me");
button.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// Do some logic here
}
}
}
In the example above, an inner class is used.
In a nutshell, there is a ton of ways you can make your button have functionality. Above are just a few examples of how to do so.
Does this clarify it a bit more, or do you have some remaining questions?
I was tasked with creating a program that displays a numeric keypad (like one on a phone) and has a screen that displays the numbers that are picked. Also included is a clear button that clears the screen.
In creating my program, I created three classes. The Phone class simply creates a JFrame that adds a PhonePanel to the screen. The PhonePanel class adds a JLabel which acts as a screen, a JButton which acts as a clear button, and a KeypadPanel which is a GridLayout of JButtons which acts as the numeric keys.
The clear button and numeric buttons both use separate action listeners. Is this the most efficient way of going about this? Is there a way I can use one action listener instead of two?
// ******************************************************************************************
// Phone.java
// David Read
// This class creates a JFrame that contains a PhonePanel. The PhonePanel provides a
// user interface that allows one to input numeric symbols on a screen and allows clearing
// of the screen.
// ******************************************************************************************
package lab5;
import javax.swing.JFrame;
public class Phone {
public static void main(String[] args)
{
// Create a JFrame object.
JFrame frame = new JFrame ("Phone");
// Set the default close operation for the JFrame.
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Add a Phone panel to the screen.
frame.getContentPane().add(new PhonePanel());
frame.pack();
frame.setVisible(true);
}
}
// ******************************************************************************************
// PhonePanel.java
// David Read
// This class creates a JPanel that includes an output label which displays inputed numeric
// symbols, a clear button that clears what is displayed on the output label, and a KeypadPanel
// which displays a GridLayout of buttons that when pressed, display their corresponding symbols
// on the output label.
// ******************************************************************************************
package lab5;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PhonePanel extends JPanel
{
private static JLabel labelOutput;
private JButton buttonClear;
//-----------------------------------------------------------------------
// Creates a JPanel that arranges three objects in a Border layout. The
// north component contains a JLabel, the east component contains a JButton
// and the center component contains a KeypadPanel.
//-----------------------------------------------------------------------
public PhonePanel()
{
// Set the layout manager, size and background color of the Phone Panel.
setLayout(new BorderLayout());
setPreferredSize (new Dimension(400, 200));
setBackground (Color.yellow);
// Output label created.
labelOutput = new JLabel(" ");
// Clear button created, assigned a button title and assigned an action listener.
buttonClear = new JButton();
buttonClear.setText("Clear");
buttonClear.addActionListener(new ClearButtonListener());
// Add the JLabel, JButton and KeypadPanel to the PhonePanel.
add(labelOutput, BorderLayout.NORTH);
add(buttonClear, BorderLayout.EAST);
add(new KeypadPanel(), BorderLayout.CENTER);
}
//-----------------------------------------------------------------------
// Adds the specified symbol to the output label.
//-----------------------------------------------------------------------
public static void addToOutputLabel(String input)
{
// Create a String object to hold the current value of the output label.
String label = labelOutput.getText();
// Append the inputed String onto the String.
label += input;
// Update the output label with the appended String.
labelOutput.setText(label);
}
//-----------------------------------------------------------------------
// Listens for the clear button to be pressed. When pressed, the output
// label is reassigned as blank.
//-----------------------------------------------------------------------
private class ClearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
labelOutput.setText(" ");
}
}
}
// ******************************************************************************************
// KeypadPanel.java
// David Read
// This class creates a JPanel that contains several buttons which when pressed, adds their
// corresponding numeric symbol to the output label in the PhonePanel.
// ******************************************************************************************
package lab5;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class KeypadPanel extends JPanel
{
private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonStar, button0, buttonNumber;
//-----------------------------------------------------------------------
// Creates a JPanel that arranges several JButtons in a GridLayout. Each
// of the buttons are assigned button titles, action listeners and
// action commands.
//-----------------------------------------------------------------------
public KeypadPanel()
{
// Set layout to a GridLayout with 4 rows and 3 columns.
setLayout(new GridLayout(4,3));
// Create new JButtons.
button1 = new JButton();
button2 = new JButton();
button3 = new JButton();
button4 = new JButton();
button5 = new JButton();
button6 = new JButton();
button7 = new JButton();
button8 = new JButton();
button9 = new JButton();
buttonStar = new JButton();
button0 = new JButton();
buttonNumber = new JButton();
// Assign button titles to the JButtons.
button1.setText("1");
button2.setText("2");
button3.setText("3");
button4.setText("4");
button5.setText("5");
button6.setText("6");
button7.setText("7");
button8.setText("8");
button9.setText("9");
buttonStar.setText("*");
button0.setText("0");
buttonNumber.setText("#");
// Create a new KeypadButtonListener.
KeypadButtonListener listener = new KeypadButtonListener();
// Assign the listener as an action listener for all of the JButton objects.
button1.addActionListener(listener);
button2.addActionListener(listener);
button3.addActionListener(listener);
button4.addActionListener(listener);
button5.addActionListener(listener);
button6.addActionListener(listener);
button7.addActionListener(listener);
button8.addActionListener(listener);
button9.addActionListener(listener);
buttonStar.addActionListener(listener);
button0.addActionListener(listener);
buttonNumber.addActionListener(listener);
// Set the action commands for all of the JButtons.
button1.setActionCommand("1");
button2.setActionCommand("2");
button3.setActionCommand("3");
button4.setActionCommand("4");
button5.setActionCommand("5");
button6.setActionCommand("6");
button7.setActionCommand("7");
button8.setActionCommand("8");
button9.setActionCommand("9");
buttonStar.setActionCommand("*");
button0.setActionCommand("0");
buttonNumber.setActionCommand("#");
// Add the JButtons to the KeypadPanel.
add(button1);
add(button2);
add(button3);
add(button4);
add(button5);
add(button6);
add(button7);
add(button8);
add(button9);
add(buttonStar);
add(button0);
add(buttonNumber);
}
//-----------------------------------------------------------------------
// Listens for all of the buttons to be pressed. When a particular button
// is pressed, the addToOutputLabel method of the PhonePanel is called
// with the input being the action command of the button pressed.
//-----------------------------------------------------------------------
private class KeypadButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Add the action command string to the output label.
PhonePanel.addToOutputLabel(e.getActionCommand());
}
}
}
In this case it is better to use two separate action listeners as functionality for clear button and for number buttons is different.
It is considered as best practice to use single responsibility principle (https://en.wikipedia.org/wiki/Single_responsibility_principle) when developing your classes. This will make your code more maintainable and easier to read and modify.
It is better to use multiple ActionListeners here, however, if you still desire to use one ActionListener instead you may make a separate class to handle all actions similar to this.
public class KeyListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//Get the name of the ActionEvent
String cmd = e.getActionCommand();
//Here the Actionevent is only checked to see if it is a "Clear" or not
//If you need to impliment more then a switch statment may be appropriate
if(cmd.equals("Clear")) {
//Clear Label with additional setter method
PhonePanel.clearLabel();
}
else {
PhonePanel.addToOutputLabel(e.getActionCommand());
}
}
I'm trying my hand at using Swing and decided to focus on using JList in conjunction with an arraylist of Objects.
I wanted to create a program that displayed a blank JList that when a button is pressed would display the contents of the arraylist as well as allow single selection that would print out what ever was selected.
My current code does all of the above however when I click on a single entry on the JList it prints it out twice. I feel like this is a simple mistake that could be easily rectified but I've been reading through it and my brain has stopped cooperating.
Any help will be greatly appreciated. Thanks in advance :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.event.*;
public class textarea {
ArrayList <Pet> petList = new ArrayList <Pet> ();
DefaultListModel model = new DefaultListModel();
JList list = new JList();
public static void main (String [] args){
textarea gui = new textarea();
gui.go();
}
public void go(){
petList.add(new Pet("Lucy","Dog",5));
petList.add(new Pet("Geoff","Cat",2));
petList.add(new Pet("Hammond","Hamster",1));
model = new DefaultListModel();
for(Pet p:petList){
model.addElement(p.toString());
}
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("view pets");
button.addActionListener(new ButtonListener());
JScrollPane scroller = new JScrollPane(list);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
list.setVisibleRowCount(4);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
String selection = (String) list.getSelectedValue();
System.out.println(selection);
}
});
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.setSize(350,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end go()
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
list.setModel(model);
}
}//end ButtonListener
}
Short answer: add if (!event.getValueIsAdjusting()) around your print like so:
list.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent event)
{
if (!event.getValueIsAdjusting())
{
String selection = (String) list.getSelectedValue();
System.out.println(selection);
}
}
});
Long answer: Two events are being fired. One fires when the mouse is clicked, and another fires when the mouse is released. We typically think of a click as a single action, but really it is composed over the mouse depression, any movements, and the mouse release. During these phases the contents of the selection can change. Run your code and try clicking on a row, dragging across to other rows, and releasing. You'll see events being fired every time the row changes. By only taking action when the value is no longer adjusting, you can fire on the 'final' state.
Source: ListSelectionEvent Javadocs and ListSelectionModel Javadocs
Just tested your code. On item selection 2 events are sent. The only difference I can see is with the isAdjusting boolean. This is set to true the first time, false the second
Anyway, it seems that this is standard behavior
Suppose I have a Java application that has more than one component in which you can enter text. Now suppose this application also has a dialog that lets you insert a single character (like the dialog in Word that comes up when you select Insert from the Edit menu) into those components. You want it to insert the character into whichever text component last had the focus.
But how do you know which text component last had the focus?
I could keep track of this manually, by having each text component report to the application whenever it gets the focus and then have the application insert the new character into whichever component that last had the focus.
But this must be a common problem (consider Paste buttons in tool bars---how does it know where to paste it into?). Is there something already built in to Swing that lets you get a handle to the last text component that had the focus? Or do I need to write this myself?
Is there something already built in to Swing that lets you get a handle to the last text component that had the focus?
You create an Action that extends TextAction. The TextAction class has a method that allows you to obtain the last text component that had focus.
Edit:
You can create your own Action and do whatever you want. The Action can then be added to any JMenuItem or JButton. For example:
class SelectAll extends TextAction
{
public SelectAll()
{
super("Select All");
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.selectAll();
}
}
If you just want to insert a character at the caret position of the text field then you can probably just do
component.replaceSelection(...);
Edit 2:
I don't understand what the confusion is with this answer. Here is a simple example:
select some text
use the mouse to click on the check box
tab or use the mouse to click on the "Cut" button
It doesn't matter that the text field doesn't currently have focus when the Action is invoked. The TextAction tracks the last text component that had focus.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextActionTest extends JFrame
{
JTextField textField = new JTextField("Select Me");
JTabbedPane tabbedPane;
public TextActionTest()
{
add(textField, BorderLayout.NORTH);
add(new JCheckBox("Click Me!"));
add(new JButton(new CutAction()), BorderLayout.SOUTH);
}
public static void main(String[] args)
{
TextActionTest frame = new TextActionTest();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
class CutAction extends TextAction
{
public CutAction()
{
super("Click to Cut Text");
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
// JTextComponent component = getTextComponent(e);
component.cut();
}
}
}
Just like suggested by #lesmana (+1 for that).
Here you have an example that shows that on focusLost the focus listener returns the previously focused component.
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Focusing
{
public static void main(String[] args)
{
JPanel p = new JPanel();
JTextField tf1 = new JTextField(6);
tf1.setName("tf1");
p.add(tf1);
JTextField tf2 = new JTextField(6);
tf2.setName("tf2");
p.add(tf2);
FocusListener fl = new FocusListener()
{
#Override
public void focusGained(FocusEvent e)
{
System.out.println("focusGained e.getSource().c=" + ((JComponent) e.getSource()).getName());
}
#Override
public void focusLost(FocusEvent e)
{
System.out.println("focusLost e.getSource().c=" + ((JComponent) e.getSource()).getName());
}
};
tf1.addFocusListener(fl);
tf2.addFocusListener(fl);
JPanel contentPane = new JPanel();
contentPane.add(p);
JFrame f = new JFrame();
f.setContentPane(contentPane);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
All the best, Boro.
I've never done this directly, but you could look into the FocusEvents and the Focus Subsystem.
Hopefully there is something in the Focus Subsystem that would fire events that you could listen for.
You can register a FocusListener to every text component. The FocusEvent object has a reference to the last component which had focus.