How to use getsource with listeners - java

I am making a tool which writes the data I give to a file. Where I need help is I have four JTextFields in which I want to apply the same mechanism to each one. That mechanism will be written independently from the frame code, and would be about checking the data input into the field and other stuff.
I wrote that mechanism to each field and it worked, and now I am thinking about shortening the code by isolating that mechanism. I know that I must use action listeners and document listeners, but I can't figure out how to make it work with <code>e.getsource()</code> method.
Here is the mechanism that I need to isolate:
txtNa_1 = new JTextField();
//the mechanism will be about setting the field text in the beginning
//to "N/A", when focused sets to "", and when
//focus is lost it preserve the index.
txtNa_1.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent arg0) {
if (txtNa_1.getText().equals("N/A")){
txtNa_1.setText("");
}}
public void focusLost(FocusEvent arg0) {
if (txtNa_1.getText().equals("")){
txtNa_1.setText("N/A");
}}});
txtNa_1.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
txtNa_23 = txtNa_2.getText();
}
public void insertUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
String txtNa_23 = txtNa_2.getText();
}
public void changedUpdate(DocumentEvent arg0) {
// TODO Auto-generated method stub
txtNa_23 = txtNa_2.getText();
}});
Simply put, can somebody explain how to cast a <code>getsource</code> along with what I am trying to make? Help appreciated.

Related

KeyListener on a disabled button

I have a series of buttons in my code. I have added key listeners to individual buttons to listen to keys, so that when user presses RIGHT, LEFT,UP DOWN, I can transfer focus to the next button.
Note: I know that TAB can be used
now everything works really great! but when the focus is at a disabled button. I am not able to listen to it.
Any suggestions, as to how I can go around the problem?
Please pardon me before hand for amateur coding style!
addEntry.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{calPeriod.setFocusable(true);
calPeriod.grabFocus();
}if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
getTime.setFocusable(true);
getTime.grabFocus();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
genChart.setFocusable(true);
genChart.grabFocus();
}
}
});

Easier way to implement MouseListener in Java

I have a more general question to ask.
When I have to implement a MouseListener in my class, the compiler automatically forces me to implement every method there is in a MouseListener interface.
Like so:
MouseListener mouseLtnr = new MouseListener()
{
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
counter++;
xs.add(MouseInfo.getPointerInfo().getLocation().x - getLocationOnScreen().x);
ys.add(MouseInfo.getPointerInfo().getLocation().y - getLocationOnScreen().y);
System.out.println(xs.get(counter-1) + " , " + ys.get(counter-1));
if(flag == false)
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
};
More often than not, I only need one or two of those. Is there a way to implement just the one I need, or do I have to deal with wasted lines of code?
Thank you for your time.
Best,
Dauta
Use a MouseAdapter, it is a basic class which implements the MouseListener (and MosueWheelListener and MouseMotionListener) interface, but provides blank implementations of all the methods, meaning you can just override the ones you want...
MouseListener mouseLtnr = new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
counter++;
xs.add(MouseInfo.getPointerInfo().getLocation().x - getLocationOnScreen().x);
ys.add(MouseInfo.getPointerInfo().getLocation().y - getLocationOnScreen().y);
System.out.println(xs.get(counter-1) + " , " + ys.get(counter-1));
if(flag == false)
repaint();
}
}
If you dig around the docs a bit, you will find a few more classes like this as well ;)
FYI: MouseInfo.getPointerInfo() will return the mouse cursor position relative to the screen, not the component that generated the event. You can also use MouseEvent#getXOnScreen and MosueEvent#getYOnScreen or SwingUtilities#convertPointToScreen(Point, Component) depending on your needs ;)

Single MouseListener Event to get text from JTextArea

I am creating a football draw app. I currently have 9 text areas which hold 6 different teams. I have attached a MouseListener to each text area. When you click on the text area, you see a new window with each team seperated into a group format.
I have an issue trying to get the text from the text areas. I could achieve this by adding a MouseListener to each individual text area but this violates the Don't Repeat Yourself (DRY) principle as far as I am aware.
I have included my code below:
gui.getTable1().addMouseListener(new tableListener());
gui.getTable2().addMouseListener(new tableListener());
gui.getTable3().addMouseListener(new tableListener());
gui.getTable4().addMouseListener(new tableListener());
gui.getTable5().addMouseListener(new tableListener());
gui.getTable6().addMouseListener(new tableListener());
gui.getTable7().addMouseListener(new tableListener());
gui.getTable8().addMouseListener(new tableListener());
gui.getTable9().addMouseListener(new tableListener());
public static class TableListener implements MouseListener {
#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
//get text from text area and pass to new GUI
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
I would like to use the TableListener private class for all my text areas instead of 9 different MouseListeners. I think this can be done in a single line but I can't think how. Can someone please help?
Attach just one instace of listener to all the textareas and use e.getSource() to get event source textarea.

Action Listener detects multiple Events for a Single Event

I have designed a panel that includes some buttons with it. Buttons are attached with an ActionListener. When ever i click on that buttons this ActionListener detects 4 events for this single click. Whereas it should detect only one. Does anybody know what exactly the reason is?
public class Buttons extends JPanel
{
private JButton undo=new JButton("Undo");
private JButton replay=new JButton("Replay");
public void paint(Graphics g)
{
super.paint(g);
super.setSize(new Dimension(560,30));
super.add(replay);
super.add(undo);
undo.setBorder(new LineBorder(Color.WHITE,3));
replay.setBorder(new LineBorder(Color.WHITE,3));
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Controler.pieces.undo();
Controler.reDraw();
}
});
replay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Dastiii");
}
});
}
}
and these events are being used here
public void undo()
{
System.out.print(Controler.allMoves.size());
if(Controler.allMoves.size()<=1)
{
init_board();
return;
}
Piece temp[][]=Controler.allMoves.get(Controler.allMoves.size()-2);
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
board[i][j].set_name(temp[i][j].get_name());
board[i][j].set_oneWay(temp[i][j].get_oneWay());
}
}
Controler.allMoves.remove(Controler.allMoves.size()-2);
}
Your registering you ActionListeners within the paint method!!
Let's not even worry about the fact that it's un-recommended to override paint
Never change or modify the state of the component or any of it's child components within in any paint method, these will be called multiple times during the execution of your application. For example, it's not unusual for a paint method to be called 2-4 times just when the main window is made visible...
public void paint(Graphics g)
{
super.paint(g);
/** All this should be done within the constructor
// If you are using a layout manager, this is pointless, if your not
// then that's another problem
super.setSize(new Dimension(560,30));
super.add(replay);
super.add(undo);
undo.setBorder(new LineBorder(Color.WHITE,3));
replay.setBorder(new LineBorder(Color.WHITE,3));
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Controler.pieces.undo();
Controler.reDraw();
}
});
replay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Dastiii");
}
});
**/
}
Take a look at:
Performing Custom Painting
Painting in AWT and Swing
For more details about how and what painting is in Swing

JTextArea row limit

So, I have a JTextArea.
I need it to be setup in a way that it prevents user from entering more than 4 rows of text.
I found a way to count lines.
But copy/paste has to be taken into account too. And I am not using monospaced font.
Is there a way of doing that taken all this into account?
why not add a DocumentListener and check the amount of lines each time text is removed, inserted or changed in the JTextArea:
JTextArea.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
check();
}
public void removeUpdate(DocumentEvent e) {
check();
}
public void insertUpdate(DocumentEvent e) {
check();
}
public void check() {
if (JTextArea.getLineCount()>4){//make sure no more than 4 lines
JOptionPane.showMessageDialog(null, "Error: Cant have more than 4 lines", JOptionPane.ERROR_MESSAGE);
}
}
});
you need to define a key listener and inside that surely we need to define implemented methods , the next code is my solution I hope it helps.
////
textfield.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(textfield.getLineCount() == maximum_number_of_your_default) {
c = ta.getCaret();
// c is an object of Caret class as : Caret c; initialization only.
a = c.getDot();
// a is an integer value initialized by zero as : int a = 0;
}
if(ta.getLineCount() > maximum_number_of_your_default){
c.moveDot(a);// To retrieve the caret to the last row.
}
// to show line segment on the output with each enter-press key :
if(e.getExtendedKeyCode() == KeyEvent.VK_ENTER)
System.out.println("!!!!!" + ta.getLineCount() + " "
+ ta.getText());
}
// default methods of KeyListener class
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
////
It my idea I hope it is correct , good luck, one world , one god , one solution for each .

Categories

Resources