How to Change Default Inputs for JComboBox and JButton - java

How do I make the Enter key trigger a JComboBox or JButton in a GUI rather than having to hit the Space key? I have an assortment of text fields and check boxes with buttons and combo boxes in between. I'd like to avoid having to switch between hitting space and enter and rather only have to hit enter for all components.
package koning.personal.dungeonsanddragons;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test {
JFrame window = new JFrame("testGUI");
JPanel windowPanel = new JPanel();
public static JLabel labelSize;
public static JComboBox<String> comboSize;
public static JLabel labelButton;
public static JButton buttonButton;
public test () {
super();
labelSize = new JLabel("Monster Size:");
String[] sizeChoices = { "None", "Tiny", "Small", "Medium", "Large", "Huge", "Colossal"};
comboSize = new JComboBox<String>(sizeChoices);
comboSize.setToolTipText("The creature's size.");
labelButton = new JLabel("Button:");
buttonButton = new JButton();
windowPanel.setLayout(new FlowLayout());
windowPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
windowPanel.add(labelSize);
windowPanel.add(comboSize);
windowPanel.add(labelButton);
windowPanel.add(buttonButton);
windowPanel.setVisible(true);
window.setSize(500, 500);
window.setLayout(new FlowLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.add(windowPanel);
comboSize.addActionListener(handler);
buttonButton.addActionListener(handler);
}
ActionHandler handler = new ActionHandler();
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent eventFocus){
if (eventFocus.getSource() == comboSize){
buttonButton.requestFocusInWindow();
}
if (eventFocus.getSource() == buttonButton){
comboSize.requestFocusInWindow();
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args) {
test GUITest = new test();
}
}

You can add a KeyListener and execute doClick
JButton btn = new JButton();
btn.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
btn.doClick();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});

If the goal is to have something happen when the enter button is pressed (pressed once and something happens with all the components) then you can add a KeyListener to the JFrame:
JFrame frame = new JFrame("Examplpe");
//here you create and add the components to the frame
and then you can add a KeyListener:
frame.addKeyListener(new KeyListener(
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode == KeyEvent.VK_ENTER){//this is the if block I'm refering to in the following explanation
//do something with all the components
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {}
}
and then when you press Enter, the code inside the if block will be executed.
Hope this helps :)

Related

Two JButtons using the same actionListener to Start/Stop Timer

I'm fairly new to Java and could do with some help. I trying to make a Timer countdown from a set time to 0. I have this functionality working fine, but I want to add functionality to allow me to stop the Timer as it's counting down.
Here is my code (I'm trying to achieve this using MVC)
This is the control part:
import java.awt.event.*;
import javax.swing.*;
public class StartButton extends JButton implements ActionListener
{
private TimerModel model;
private Timer timer;
private boolean isStarted;
public StartButton(String buttonText, TimerModel model)
{
super(buttonText);
addActionListener(this);
this.model = model;
isStarted = false;
}
public void actionPerformed(ActionEvent evt)
{
if(!isStarted)
{
timer = new Timer(1000, this);
timer.start();
isStarted = true;
}
model.timerCountdown();
}
public void stopTimer()
{
timer.stop();
}
}
I have looked at some other similar issues online and I tried this within the constructor (Note: I didn't use implements ActionListener, and removed the actionPerformed method I had above):
if(buttonText.equals("Start"))
{
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(!isStarted)
{
timer = new Timer(1000, this);
timer.start();
isStarted = true;
}
model.timerCountdown();
}
});
}
if(buttonText.equals("Stop"))
{
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
timer.stop();
}
});
}
Now this part handles the counting down ok, but when I click the stop button it shows an exception(See stack trace here), and it continues to count down.
I have limited knowledge, but I guess it's something to do with the way I'm trying to stop the Timer.
I would appreciate it if someone could point me in the right direction, or at least explain to me why this happens.
Again, if you're not changing the basic behavior of the JButton itself, such as how it is drawn, but instead are only changing the button's title and behavior when pressed, then don't extend JButton. Instead give each button its own Action, an object from a class that extends from AbstractAction. Consider these guys as similar to ActionListeners on steroids. They have the same abilities as ActionListeners and then some since they can easily change the button's title, whether it is enabled or not, its mnemonic, icon,...
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyTimerGui {
private static final String TITLE = "Flashing Label";
private static final int TIMER_DELAY = 200;
private static final int GAP = 3;
private static final float LABEL_POINTS = 32F;
private JPanel mainPanel = new JPanel();
private JLabel flashyLabel = new JLabel(TITLE, SwingConstants.CENTER);
private Timer timer = new Timer(TIMER_DELAY, new TimerListener());
public MyTimerGui() {
Font font = flashyLabel.getFont();
font = font.deriveFont(LABEL_POINTS);
flashyLabel.setFont(font);
flashyLabel.setOpaque(true);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
buttonPanel.add(new JButton(new StartAction(this, "Start", KeyEvent.VK_S)));
buttonPanel.add(new JButton(new StopAction(this, "Stop", KeyEvent.VK_T)));
buttonPanel.add(new JButton(new ExitAction(this, "Exit", KeyEvent.VK_X)));
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.setLayout(new BorderLayout());
mainPanel.add(flashyLabel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.PAGE_END);
}
public JComponent getMainComponent() {
return mainPanel;
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
flashyLabel.setForeground(null);
flashyLabel.setBackground(null);
}
public void exit() {
timer.stop();
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
private class TimerListener implements ActionListener {
private final Color foreground1 = Color.green;
private final Color background1 = Color.red;
#Override
public void actionPerformed(ActionEvent aEvt) {
Color fg = flashyLabel.getForeground();
if (foreground1.equals(fg)) {
flashyLabel.setForeground(null);
flashyLabel.setBackground(null);
} else {
flashyLabel.setForeground(foreground1);
flashyLabel.setBackground(background1);
}
}
}
private class StartAction extends AbstractAction {
private MyTimerGui myTimerGui;
public StartAction(MyTimerGui myTimerGui, String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.myTimerGui = myTimerGui;
}
#Override
public void actionPerformed(ActionEvent e) {
myTimerGui.start();
}
}
private class StopAction extends AbstractAction {
private MyTimerGui myTimerGui;
public StopAction(MyTimerGui myTimerGui, String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.myTimerGui = myTimerGui;
}
#Override
public void actionPerformed(ActionEvent e) {
myTimerGui.stop();
}
}
private class ExitAction extends AbstractAction {
private MyTimerGui myTimerGui;
public ExitAction(MyTimerGui myTimerGui, String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.myTimerGui = myTimerGui;
}
#Override
public void actionPerformed(ActionEvent e) {
myTimerGui.exit();
}
}
private static void createAndShowGui() {
MyTimerGui myTimerGui = new MyTimerGui();
JFrame frame = new JFrame("MyTimer");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(myTimerGui.getMainComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I agree with the comments that say you shouldn't be extending a JButton. Maybe the logic should be carried out in the main class of your application, the same class that class that deals with the creation and storage of the components.
But I digress. To answer your question, I think there are really two ways to approach this. Either (A) have the actionListener stored within your class as you did in your code or (B) write an actionListener outside of the object itself.
Was the constructor you tried to implement this in the main class constructor?
I think you need something like the following (this, again, is in the main class):
StartButton start = new JButton("Start");
StopButton stop = new JButton("Stop");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// called when the button is pressed
buttonPressed();
}
});
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// called when the button is pressed
buttonPressed();
}
});
Then you would write this method in the same class:
private void buttonPressed() {
System.out.println("Button pressed!");
}
I just whipped up a quick test of this, so I can confirm that this method works.
PS: I would also suggest having the button contain a boolean state instead of checking for the text of the button, if you do intend to keep using the StartButton and associated classes.

ActionListener is only counting left mouse click

I learned this code from some tutorial but it only counts left mouse clicks. I try with MouseListener but it kept counting while the timer came to 0. And with ActionListener it isn't counting the right mouse clicks. Any suggestions? Maybe its a foolish question but I'm new here.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class game extends JFrame
{
private static final int SwingConstants=0;
Timer timer;
int timercounter;
int clickcounter;
JLabel directions,entertime,clicklabel,timeleft,label;
JButton startbutton,clickbutton;
JTextField tf;
JMenuBar menubar;
JMenu file,help;
JMenuItem reset,exit,mhelp;
JFrame frame=new JFrame();
public game()
{
Container pane=this.getContentPane();
pane.setLayout(new GridLayout(3,1,2,2));
menubar=new JMenuBar();
setJMenuBar(menubar);
file=new JMenu("File");
menubar.add(file);
help=new JMenu("Help");
menubar.add(help);
reset=new JMenuItem("Reset");
file.add(reset);
exit=new JMenuItem("Quit");
file.add(exit);
mhelp=new JMenuItem("More Help!!");
help.add(mhelp);
ResetClass rc=new ResetClass();
reset.addActionListener(rc);
ExitClass ec=new ExitClass();
exit.addActionListener(ec);
MhelpClass mc=new MhelpClass();
mhelp.addActionListener(mc);
JPanel top=new JPanel();
top.setLayout(new GridLayout(1,1));
directions=new JLabel("Enter time & press <Click Here> REPEATEDLY!!");
top.add(directions);
pane.add(top);
JPanel middle=new JPanel();
middle.setLayout(new GridLayout(1,3));
entertime=new JLabel("Enter Time (sec):");
middle.add(entertime);
tf=new JTextField();
middle.add(tf);
startbutton=new JButton("Click Here");
middle.add(startbutton);
pane.add(middle);
JPanel bottom=new JPanel();
bottom.setLayout(new GridLayout(1,3));
clickbutton=new JButton("Click Here!");
clickbutton.setEnabled(false);
bottom.add(clickbutton);
clicklabel=new JLabel("Clicks: 0");
bottom.add(clicklabel);
timeleft=new JLabel("Time left: ?");
bottom.add(timeleft);
pane.add(bottom);
StartButtonClass sbc=new StartButtonClass();
startbutton.addActionListener(sbc);
ClickButtonClass cbc=new ClickButtonClass();
clickbutton.addActionListener(cbc);
}
public class StartButtonClass implements ActionListener
{
#Override
public void actionPerformed(ActionEvent sbc)
{
try
{
int timeCount=(int)(Double.parseDouble(tf.getText()));
if(timeCount<=0)
{
tf.setText("Positive number!");
//startbutton.setEnabled(false);
}
else
{
timeleft.setText("Time left: "+timeCount);
TimeClass tc=new TimeClass(timeCount);
timer=new Timer(1000,tc);
timer.start();
startbutton.setEnabled(false);
clickbutton.setEnabled(true);
}
}
catch(NumberFormatException ex)
{
tf.setText("Number only!");
}
}
}
public class ClickButtonClass implements MouseListener
{
public void mouseReleased(MouseEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
#Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e)
{
// TODO Auto-generated method stub
}
}
public class TimeClass implements ActionListener
{
int timerCounter;
public TimeClass(int timerCounter)
{
this.timerCounter=timerCounter;
}
public void actionPerformed(ActionEvent tc)
{
timerCounter--;
if(timerCounter>=1)
{
timeleft.setText("Time left: "+timerCounter);
}
else
{
timer.stop();
timeleft.setText("Done!");
clickbutton.setEnabled(false);
Toolkit.getDefaultToolkit().beep();
}
}
}
public class ResetClass implements ActionListener
{
public void actionPerformed(ActionEvent rc)
{
clickbutton.setEnabled(false);
startbutton.setEnabled(true);
clickcounter=0;
clicklabel.setText("Clicks: 0");
tf.setText("");
timeleft.setText("Time left: ?");
}
}
public class ExitClass implements ActionListener
{
public void actionPerformed(ActionEvent ec)
{
System.exit(0);
}
}
public class MhelpClass implements ActionListener
{
public void actionPerformed(ActionEvent mc)
{
JOptionPane.showMessageDialog(null, "Read the Readme file carefully!!", "Help!!", JOptionPane.PLAIN_MESSAGE);
}
}
}
Use this it will let you see right mouse clicks
class MyMouseListener implements MouseListener{
#Override
public void mouseReleased(MouseEvent arg0) {
if(SwingUtilities.isRightMouseButton(arg0)&&clickButton.isEnabled()){
//my code
}
}

KeyListener won't listen on JPanel

It's a very simple program, but for some reason when I debug it and set breakpoints at the keyPressed, keyReleased and keyTyped method, the program never stops there.
mainKeyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("KEY PRESSED");
repaint();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
};
Here I add it to a JPanel, which is the exact size of the frame and the only object on it:
JPanel backgroundPanel = new JPanel();
backgroundPanel.setBounds(0,0, 400, 500);
backgroundPanel.addKeyListener(mainKeyListener);
backgroundPanel.setFocusable(true);
getContentPane().add(backgroundPanel);
Your problem is laying in focused element. I think that your panel lost the focus.
Note:
To fire keyboard events, a component must have the keyboard focus. It can be solved in many ways for your example you can use KeyboardFocusManager for example like this:
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if(focusManager.getFocusOwner()!=backgroundPanel){
focusManager.redispatchEvent(backgroundPanel,e);
return true;}
else return false;
}
});
Also try to use Key Bindings http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Hi this should work for you.
public class Gui extends JFrame
{
private JPanel backgroundPanel = new JPanel();
public Gui() throws HeadlessException
{
this.setLayout(new GridLayout(1,1));
setPanelProps();
backgroundPanel.addKeyListener(createListener());
this.add(backgroundPanel);
this.setVisible(true);
this.setSize(new Dimension(400,500));
}
public void setPanelProps(){
backgroundPanel.setBounds(0, 0, 400, 500);
backgroundPanel.setSize(new Dimension(400,500));
backgroundPanel.setFocusable(true);
backgroundPanel.setBackground(new Color(50,60,70));
}
public KeyListener createListener(){
return new KeyListener() {
#Override
public void keyTyped(KeyEvent e)
{
System.out.println("KEY TYPED");
}
public void keyPressed(KeyEvent e) {
System.out.println("KEY PRESSED");
repaint();
}
#Override
public void keyReleased(KeyEvent e)
{
System.out.println("KEY RELEASED");
}
};
}
}
public class GuiRun
{
public static void main(String[] args)
{
Gui gui = new Gui();
}
}

No up state JButton

I'm trying to change to appearance of my JButton so that the button have no up state.
Currently i have something like this:
And i would like something like this:(comming from NetBeans)
In other words, I only want the image of the button to be visible when the button does not have any kind of focus. But when the user click or roll over it, it should act exactly the same as a regular button.
more examples:
no focus
roll over
click
I use a inner class for my button. It look like this:
private class CustumJButton extends JButton
{
public CustumJButton(Icon icon)
{
super(icon);
int size = 30;
setPreferredSize(new Dimension(size, size));
setFocusable(false);
}
}
Thanks ayoye.
You can achieve this using setBorderPainted() and setContentAreaFilled() methods. Here is the short Demo of what you are looking for. I hope it would give you rough figure to how to achieve your task.:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CustomJButton extends JButton
{
public CustomJButton(String icon)
{
super(icon);
/*int size = 30;
setPreferredSize(new Dimension(size, size));*/
addFocusListener(new ButtonFocusAdapter());
addMouseListener(new ButtonMouseAdapter());
setContentAreaFilled(false);
setBorderPainted(false);
//setFocusable(false);//Don't use this method. This would avoid the focus event on JButton
}
private void decorateButton()
{
setContentAreaFilled(true);
setBorderPainted(true);
}
private void unDecorateButton()
{
setContentAreaFilled(false);
setBorderPainted(false);
}
private class ButtonFocusAdapter extends FocusAdapter
{
#Override
public void focusGained(FocusEvent evt)
{
decorateButton();
}
#Override
public void focusLost(FocusEvent evt)
{
unDecorateButton();
}
}
private class ButtonMouseAdapter extends MouseAdapter
{
#Override
public void mouseEntered(MouseEvent evt)
{
decorateButton();
}
#Override
public void mouseExited(MouseEvent evt)
{
unDecorateButton();
}
}
}
public class ButtonFrame extends JFrame
{
public void createAndShowGUI()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
for (int i = 0; i < 4 ; i++ )
{
CustomJButton cb = new CustomJButton("Button "+i);
c.add(cb);
}
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String st[])
{
SwingUtilities.invokeLater( new Runnable()
{
#Override
public void run()
{
ButtonFrame bf = new ButtonFrame();
bf.createAndShowGUI();
bf.setLocationRelativeTo(null);
}
});
}
}
I guess you need to use these two things to make it work, setBorderPainted(boolean) and setContentAreaFilled(boolean)
buttonObject.setBorderPainted(false);
buttonObject.setContentAreaFilled(false);
as cited in this example for changing appearance of JButton by #mKorbel
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ButtonDemo
{
private JButton demoButton;
private ImageIcon buttonImage;
private void displayGUI()
{
JFrame frame = new JFrame("Button Demo Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
try
{
//buttonImage = new ImageIcon(ImageIO.read(
// getClass().getResource("/image/bulb.gif")));
buttonImage = new ImageIcon(ImageIO.read(
new URL("http://gagandeepbali.uk.to/"
+ "gaganisonline/swing/downloads/"
+ "images/bulb.gif")));
}
catch(Exception e)
{
e.printStackTrace();
}
demoButton = new JButton(buttonImage);
setExceptionalState(demoButton);
demoButton.addMouseListener(new MouseAdapter()
{
#Override
public void mouseEntered(MouseEvent me)
{
setNormalState(demoButton);
}
#Override
public void mouseExited(MouseEvent me)
{
setExceptionalState(demoButton);
}
});
contentPane.add(demoButton);
frame.setContentPane(contentPane);
frame.setSize(300, 100);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void setExceptionalState(JButton button)
{
button.setBorderPainted(false);
button.setContentAreaFilled(false);
}
private void setNormalState(JButton button)
{
button.setBorderPainted(true);
button.setContentAreaFilled(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new ButtonDemo().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
You would set the default state for the button as:
button.setBorderPainted(false);
Then you would need to use a MouseListener:
on mouseEntered you would use
button.setBorderPainted(true);
and on mouse exited you would use
button.setBorderPainted(false);
You should check out the skinnable "Synth Look and Feel", but also be aware that Swing will be deprecated and replaced by JavaFX in the long run. If you are building a new application, you might want to consider using JavaFX which can be skinned with CSS to achieve the effect you are looking for.

Can you link values for two JFormattedTextFields?

I've got an interface with 2 JFormattedTextFields for which I need the values (not just the displayed text) to be identical. Ideally they should both be editable, with a change in one being mirrored in the other.
I started by just sharing a single Document between the two, but quickly ran into the problem that this only links the displayed text, not the underlying value. (Silly me!)
I haven't tried adding reciprocal PropertyChangeListeners for the "value" property because I would expect that to set up an infinite loop of modification.
Am I missing something? Is there some way to do this? Or am I stuck with only allowing users to edit one of the two and only having the value propagate in one direction?
Thank you!
I need the values (not just the displayed text) to be identical.
Ideally they should both be editable, with a change in one being
mirrored in the other.
use DocumentListener,
for example (only the one directions)
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class TextLabelMirror {
private JPanel mainPanel = new JPanel();
private JTextField field = new JTextField(20);
private JTextField field1 = new JTextField(20);
public TextLabelMirror() {
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
field1.setText(field.getText());
}
});
}
});
mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
mainPanel.add(field);
mainPanel.add(field1);
}
public JComponent getComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("TextLabelMirror");
frame.getContentPane().add(new TextLabelMirror().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
You can use a key listener. You simply add a key listener to both fields using the below code. the reason you need the other events is it will throw errors unless you have them in the code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CreateGrid
{
JFrame thisframe;
JFormattedTextField jFormattedTextField1, jFormattedTextField2;
public CreateGrid()
{
GridLayout thislayout = new GridLayout(0,2);
thisframe = new JFrame();
thisframe.setLayout(thislayout);
jFormattedTextField1 = new JFormattedTextField();
jFormattedTextField2 = new JFormattedTextField();
jFormattedTextField1.addKeyListener(new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
JFormattedTextField textField = (JFormattedTextField) e.getSource();
String text = textField.getText();
jFormattedTextField2.setText(text);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
}
});
jFormattedTextField2.addKeyListener(new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
JFormattedTextField textField = (JFormattedTextField) e.getSource();
String text = textField.getText();
jFormattedTextField1.setText(text);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
}
});
thisframe.add(jFormattedTextField1);
thisframe.add(jFormattedTextField2);
thisframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisframe.setVisible(true);
thisframe.pack();
}
public static void main(String args[])
{
new CreateGrid();
}
}
I have tested this out and it works perfectly what ever you type into one field will show up in the other as you type it.

Categories