View Single Post
  #9 (permalink)  
Old 07-02-2008, 10:16 PM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
TextAction was designed for this. The nested classes in DefaultEditorKit extend it.
Code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class TextFocus { private JMenuBar getMenuBar() { JMenu menu = new JMenu("edit"); //DefaultEditorKit kit = new DefaultEditorKit(); //Action[] actions = kit.getActions(); //for(int i = 0; i < actions.length; i++) // System.out.println(actions[i].getValue(Action.NAME)); Action action = new DefaultEditorKit.CutAction(); action.putValue(Action.NAME, "cut"); menu.add(action); action = new DefaultEditorKit.CopyAction(); action.putValue(Action.NAME, "copy"); menu.add(action); action = new DefaultEditorKit.PasteAction(); action.putValue(Action.NAME, "paste"); menu.add(action); menu.add(new SelectAction()); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); return menuBar; } private class SelectAction extends TextAction { SelectAction() { super(DefaultEditorKit.selectAllAction); super.putValue(NAME, "selectAll"); } public void actionPerformed(ActionEvent e) { getFocusedComponent().selectAll(); } } private JPanel getContent() { String[] strs = { "red", "green", "yellow", "blue" }; JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1.0; gbc.weighty = 1.0; for(int i = 0; i < 4; i++) { JTextField tf = new JTextField(strs[i], 12); gbc.gridwidth = ((i+1) % 2 == 0) ? gbc.REMAINDER : 1; panel.add(tf, gbc); } return panel; } public static void main(String[] args) { TextFocus test = new TextFocus(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(test.getMenuBar()); f.add(test.getContent()); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); } }
Reply With Quote