Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JTextArea and the Tab Key

843807Aug 13 2010 — edited Aug 13 2010
Hello,

I'd like to make it to where the tab key simply switches the focus of the cursor to another element, without inserting into the JTextArea. Is there any way I can do this? This is the code I'm currently using.
package test;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class SSCCE implements KeyListener
{
	private static JTextArea ta[] = {new JTextArea(1,15),new JTextArea(1,15)};

	@Override
	public void keyPressed(KeyEvent e) {}

	@Override
	public void keyReleased(KeyEvent e)
	{
		JTextArea src = (JTextArea)e.getSource();
		if(e.getKeyCode()==9)
		{
			src.setText(src.getText().replace("\t",""));
			if(e.getSource() == ta[0])
			{
				ta[1].requestFocus();
			}
			else
			{
				ta[0].requestFocus();
			}
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {}

	public static void main(String args[])
	{
		JPanel p[] = {new JPanel(), new JPanel()};
		JFrame f = new JFrame("Test");
		
		ta[0].setFont(new Font("Courier New",Font.PLAIN,12));
		ta[0].addKeyListener(new SSCCE());
		ta[1].setFont(new Font("Courier New",Font.PLAIN,12));
		ta[1].addKeyListener(new SSCCE());
		p[0].add(ta[0]);
		p[1].add(ta[1]);
		f.setSize(152,80);
		f.setLocationRelativeTo(null);
		f.add(p[0],BorderLayout.NORTH);
		f.add(p[1],BorderLayout.SOUTH);
		f.setVisible(true);
	}
}
Edited by: ElectrifiedBrain on Aug 13, 2010 12:09 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 10 2010
Added on Aug 13 2010
3 comments
294 views