Tuesday, November 15, 2011

How do I get the focus of a java swing component?

I want to make a button that deletes what a user just typed into component (jtextpane, jtextfield, or jtable). What methods can I use to see what swing the user is focused on to clear it?|||Since as soon as you select the button - the button will gain focus - I would add a focus listener to each component and keep track of which one was the last to loose focus. Take a look at the following for some ideas (I'm sure there are other ways to do this)





import javax.swing.*;


import java.awt.event.*;





public class Main


{


public static void main(String[] args)


{


MyFrame frame = new MyFrame();


frame.setDefaultCloseOperation(


JFrame.EXIT_ON_CLOSE);


frame.setVisible(true);


}


}





class MyFrame extends JFrame


{


public MyFrame()


{


setSize(500,500);


setTitle("Test Focus");


add(new MyPanel());


}


}





class MyPanel extends JPanel


{


public MyPanel()


{


table = new JTable(2,2);


table.addFocusListener(new MyListener(TABLE));


field = new JTextField(10);


field.addFocusListener(new MyListener(FIELD));


pane = new JTextPane();


pane.addFocusListener(new MyListener(PANE));


pane.setSize(10,10);


button = new JButton("Focus");


button.addFocusListener(new MyListener(BUTTON));


button.addActionListener(


new ActionListener(){


public void actionPerformed(


ActionEvent event) { focus(); }


});





add(table);


add(field);


add(pane);


add(button);


}





private void focus()


{


switch(last)


{


case TABLE: System.out.println("Delete Table"); break;


case FIELD: System.out.println("Delete Field"); break;


case PANE: System.out.println("Delete Pane"); break;


}


}





private class MyListener implements FocusListener


{


public MyListener(int type)


{


this.type = type;


}


public void focusLost(FocusEvent event)


{


last = type;


}


public void focusGained(FocusEvent event){}


private int type;


}





private JButton button;


private JTable table;


private JTextField field;


private JTextPane pane;


private int last = 0;


private static final int BUTTON = 0;


private static final int TABLE = 1;


private static final int FIELD = 2;


private static final int PANE = 3;


}

No comments:

Post a Comment