我在我的代码中添加了copy和clear并且它们工作正常,但我仍然遇到cut和find命令的问题,该命令允许用户在输出区域中搜索指定的测试
public class rr extends JFrame实现了ActionListener {
private JTextArea outputArea;
public rr()
{
associatedTextSet = new HashSet<String>();
initialiseWindow();
}
private void initialiseWindow()
{
setTitle("rr");
setLocation(50, 50);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
contentPane = getContentPane();
contentPane.setBackground(Color.magenta);
contentPane.setLayout( new BoxLayout(contentPane, BoxLayout.Y_AXIS) );
WindowAdapter windowListener = new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
ActionEvent action = new ActionEvent(this, 0, "Exit");
actionPerformed(action);
} };
addWindowListener(windowListener);
setupMenusAndActions();
setUpOutputArea();
setVisible(true);
}
private void setUpOutputArea()
{
outputArea = new JTextArea();
outputArea.setFont(new Font("Courier", Font.PLAIN, 12));
outputArea.setEditable(false);
outputArea.setBackground(Color.white);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setMargin(new Insets( 5, 10, 5, 10));
JScrollPane areaScrollPane = new JScrollPane(outputArea);
areaScrollPane.setPreferredSize( new Dimension(WIDTH, HEIGHT) );
Border b = BorderFactory.createLoweredBevelBorder();
areaScrollPane.setViewportBorder(BorderFactory.createTitledBorder(b, "Output View"));
contentPane.add(areaScrollPane);
pack();
TextAreaOutputStream textOutput = new TextAreaOutputStream(outputArea);
PrintStream capturedOutput = new PrintStream(textOutput);
System.setOut(new PrintStream(capturedOutput)); // divert StandardOutput to capturedOutput
}
private void setupMenusAndActions()
{
JMenuBar menuBar = new JMenuBar();
// Edit menu
editMenu = setupMenu(menuBar, "Edit", 'E');
setupMenuItem(editMenu, "Copy", "Copy selected text from Output area to clipboard", 'C', true, KeyStroke.getKeyStroke("ctrl C"));
setupMenuItem(editMenu, "Cut", "Cut selected text from Output area to clipboard", 'T', true );
setupMenuItem(editMenu, "Find", " Find selected text from Output area to clipboard", 'F', true );
setupMenuItem(editMenu, "Clear", "Clear Output area", 'L', true, KeyStroke.getKeyStroke("ctrl F3"));
setJMenuBar(menuBar);
}
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
//
// Edit menu
//
else if( action.equals("Copy") )
{
outputArea.copy();
}
else if(action.equals("Cut"))
{
outputArea.cut();
}
else if( action.equals("Clear") )
{
outputArea.selectAll();
outputArea.setText("");
}
else if(action.equals("Find"))
{
}
}
答案 0 :(得分:2)
,但我仍然有切割问题
使用EditorKit提供的默认操作:
JMenuItem cut = new DefaultEditorKit.CutAction();
您也可以执行此操作进行复制。
通常,您应该扩展TextAction并为每个函数创建自定义Action,而不是共享公共侦听器。类似的东西:
class ClearAction extends TextAction
{
public ClearAction()
{
super("Clear");
}
public void actionPerformed(ActionEvent e)
{
getFocusedComponent().setText("");
}
}
答案 1 :(得分:0)