gpt4 book ai didi

java - 为我正在创建的 GUI 中的 JMenuItem "Copy"提供低级功能

转载 作者:行者123 更新时间:2023-12-02 05:13:40 24 4
gpt4 key购买 nike

我正在创建一个具有 JMenuItems(例如复制和粘贴)的低级 GUI。我需要创建一个 selectText() 方法,用于复制已合并到 JScrollPane 中的 JTextArea 中的选定文本。我正在尝试找出我应该使用的代码。我尝试过使用 getSelectedText() 但总是返回“null”。我有一些操作仍然没有任何功能,或者显示一个消息对话框,显示“有效”,以知道我已经添加了 ActionEvent,但没有任何实际功能。最终,我尝试将功能添加到 JMenuItem“复制”中,以便我可以使用 JMenuItem“列表文件”打开文件(这只打开基本文件,例如 .txt),然后复制 JTextArea 中显示的内容使用鼠标选择所需的文本,然后转到“工具”>“编辑”>“复制”,并使用 JMenuItem“复制”中集成的功能选择文本并使用名为 selectText() 的方法将其存储在字符串变量中。还要忽略 BasicFile 类中的一些方法,因为我从必须制作的另一个程序中重新使用了它。

这是我的代码:

MyJFrame.java

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MyJFrame;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;

/**
*
* @author Alejandro
*/
public class MyJFrame extends JFrame{

public MyJFrame(String title) throws HeadlessException {
super(title);
super.getContentPane().setBackground(Color.lightGray);
super.setPreferredSize(new Dimension(800, 600));
super.setLocation(500,300);
super.pack();

//CREATING MENU BAR
JMenuBar menuBar = new JMenuBar();
for(int i = 0; i < Constants.menus.length; i++)
{
JMenu newMenu = new JMenu(Constants.menus[i]);
//CREATING MENU FOR FILE
if(Constants.menus[i].equals("File"))
{
for(int fileItemCounter = 0; fileItemCounter < Constants.fileMenuChoices.length; fileItemCounter++)
{
//ADDING SEPARATOR WHEN NEEDED
if(Constants.fileMenuChoices[fileItemCounter].equals("*"))
{
newMenu.addSeparator();
}
else if(Constants.fileMenuChoices[fileItemCounter].equals("New"))
{
JMenuItem newMenuItem = new JMenuItem(new AbstractAction("New")
{
public void actionPerformed(ActionEvent e)
{
// Button pressed logic goes here
MyJFrame childFrame = new MyJFrame("New File");
childFrame.setLocation(600, 400);
}
});
newMenu.add(newMenuItem);
}
else if(Constants.fileMenuChoices[fileItemCounter].equals("List Files"))
{
JMenuItem newMenuItem = new JMenuItem(new AbstractAction("List Files")
{
public void actionPerformed(ActionEvent e)
{
// Button pressed logic goes here
try
{
BasicFile f = new BasicFile();
DisplayText textToBeDisplayed = new DisplayText(f.getName(), f.getContents());
JTextArea text = new JTextArea(textToBeDisplayed.getFileContents(),50, 50);
JScrollPane pane = new JScrollPane(text);
MyJFrame fileOpened = new MyJFrame(textToBeDisplayed.getFileName());
fileOpened.add(pane);
fileOpened.setLocation(600, 400);
}
catch(FileNotFoundException x)
{

}
}
});
newMenu.add(newMenuItem);
}
else
{
JMenuItem newMenuItem = new JMenuItem(Constants.fileMenuChoices[fileItemCounter]);
newMenu.add(newMenuItem);
}
}
}
//CREATING MENU FOR TOOLS
if(Constants.menus[i].equals("Tools"))
{
for(int toolsItemCounter = 0; toolsItemCounter < Constants.toolsMenuChoices.length; toolsItemCounter++)
{
//CREATING SUBMENU FOR MENU ITEM "EDIT"
if(Constants.toolsMenuChoices[toolsItemCounter].equals("Edit"))
{
JMenu newSubMenu = new JMenu(Constants.toolsMenuChoices[toolsItemCounter]);
for(int editMenuChoicesCounter = 0; editMenuChoicesCounter < Constants.editMenuChoices.length; editMenuChoicesCounter++)
{
if(Constants.editMenuChoices[editMenuChoicesCounter].equals("Copy"))
{
JMenuItem menuItem = new JMenuItem(new AbstractAction("Copy")
{
public void actionPerformed(ActionEvent e)
{
// Button pressed logic goes here
JOptionPane.showMessageDialog(null, "works");
}
});
newSubMenu.add(menuItem);
}
else if(Constants.editMenuChoices[editMenuChoicesCounter].equals("Paste"))
{
JMenuItem menuItem = new JMenuItem(new AbstractAction("Paste")
{
public void actionPerformed(ActionEvent e)
{
// Button pressed logic goes here
JOptionPane.showMessageDialog(null, "works");
}
});
newSubMenu.add(menuItem);
}
newMenu.add(newSubMenu);
}
}
else
{
JMenuItem newMenuItem = new JMenuItem(Constants.toolsMenuChoices[toolsItemCounter]);
newMenu.add(newMenuItem);
}
}
}
menuBar.add(newMenu);
}
super.setJMenuBar(menuBar);
super.setVisible(true);
}

public static void main(String[] args) {
MyJFrame mainFrame = new MyJFrame("My First GUI");
}
}

DisplayText.java

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MyJFrame;

import javax.swing.JTextArea;

/**
*
* @author Alejandro
*/
public class DisplayText {
String fileName;
String fileContents;

public DisplayText(String fileName, String fileContents) {
this.fileName = fileName;
this.fileContents = fileContents;
}

public String getFileName() {
return fileName;
}

public String getFileContents() {
return fileContents;
}

// public String selectText()
// {
// ;
// }
}

BasicFile.java

 /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MyJFrame;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StreamTokenizer;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
*
* @author Alejandro
*/
public class BasicFile
{
File f;
File backupFile;

public BasicFile()
{
JFileChooser choose = new JFileChooser(".");
int status = choose.showOpenDialog(null);

try
{
if (status != JFileChooser.APPROVE_OPTION)
throw new IOException();
f = choose.getSelectedFile();
if (!f.exists())
throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
display(e.toString(), "File not found ....");
}
catch(IOException e)
{
display(e.toString(), "Approve option was not selected");
}
}

void display(String msg, String s)
{
JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}

// Other methods may be included

String getContents() throws FileNotFoundException{
String content = "";
Scanner readFile = new Scanner(f);
while(readFile.hasNext()){
content = content + readFile.nextLine() + "\n";
}
return content;
}

long getFileSize(){
return f.length();
}

String getPath(){
return f.getPath();
}

String getName(){
return f.getName();
}

String backUpFile(){
return "File successfully backed up!";
}

String displayFileInfo(){
File parentDirectory = new File(f.getParent());
File[] filesAndDirectories = parentDirectory.listFiles();
String filesAndDirectoriesInfo = "";
for(File f : filesAndDirectories){
filesAndDirectoriesInfo = filesAndDirectoriesInfo + f.getAbsolutePath() + "\n";
}
return "File name: " + f.getName() + "\nAbsolute Path: " + f.getAbsolutePath() + "\nFiles and Directories:\n"
+ filesAndDirectoriesInfo + "\nFile Size: " + f.length() + " bytes";
}


void backupFile() throws FileNotFoundException
{
JOptionPane.showMessageDialog(null, "Please select or create a file for the backup", "File Backup", JOptionPane.INFORMATION_MESSAGE);
JFileChooser backupChoose = new JFileChooser(".");
int backupStatus = backupChoose.showSaveDialog(null);
try
{
if (backupStatus != JFileChooser.APPROVE_OPTION)
throw new IOException();
backupFile = backupChoose.getSelectedFile();
}
catch(IOException e)
{
display(e.toString(), "Approve option was not selected");
}
DataInputStream in = null;
DataOutputStream out = null;
try
{
in = new DataInputStream(new FileInputStream(f));
out = new DataOutputStream(new FileOutputStream(backupFile));
try
{
while (true)
{
byte data = in.readByte();
out.writeByte(data);
}
}
catch(EOFException e)
{
JOptionPane.showMessageDialog(null, "File was successfully backed up!",
"Complete", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "File not found",
"Error", JOptionPane.INFORMATION_MESSAGE);
}
}
finally
{
try
{
in.close();
out.close();
}
catch(Exception e)
{
display(e.toString(), "Error");
}
}
}

String countFile()
{
try
{
int wordCount = 0;
int numberCount = 0;
int lineCount = 1;
int charCount = 0;
int totalWords = 0;

FileReader reader = new FileReader(f);
StreamTokenizer st = new StreamTokenizer(reader);
st.eolIsSignificant(true);
st.whitespaceChars(0, ' ');
st.wordChars('a','z');
st.wordChars('A','Z');
do{
if(st.ttype == StreamTokenizer.TT_NUMBER){
numberCount++;
charCount++;
}
if(st.ttype == StreamTokenizer.TT_WORD){
charCount += st.sval.length();
wordCount++;
}
if(st.ttype == StreamTokenizer.TT_EOL){
lineCount++;
}
if(st.ttype == StreamTokenizer.TT_EOF){
break;
}
}while(st.nextToken() != StreamTokenizer.TT_EOF);
reader.close();
totalWords = numberCount + wordCount;
return f.getName() + " has " + lineCount + " lines, "
+ totalWords + " words, " + numberCount + " numbers, " + charCount + " characters. (Approximately)";
}
catch(IOException e)
{
display(e.toString(), "Error");
}
return "null";
}

public String findString(String line, String currentLine, String stringToSearch, LineNumberReader lnr) throws Exception
{
if(currentLine != null)
{
String s = currentLine.toLowerCase();

if(s.contains(stringToSearch.toLowerCase()))
{
line = line + "\nLine " + lnr.getLineNumber() + ": " + currentLine;
}
return findString(line, lnr.readLine(), stringToSearch, lnr );
}
return line;
}

String search() throws FileNotFoundException, IOException, Exception{
String stringSearched = JOptionPane.showInputDialog("Enter string to search for: ");
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
String results = findString("", lnr.readLine(), stringSearched, lnr);
return results;
}
}

Constants.java

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package MyJFrame;

/**
*
* @author Alejandro
*/
public interface Constants {

public static final String[] menus = {"File","Tools","Help"};

public static final String[] fileMenuChoices = {"New", "List Files","*", "Save As", "*", "Close"};

public static final String[] toolsMenuChoices = {"Sort", "Search", "Edit"};

public static final String[] editMenuChoices = {"Copy", "Paste"};

}

最佳答案

您应该考虑使用JTextArea的内置功能...

您可能还想看看 How to Use Actions

关于java - 为我正在创建的 GUI 中的 JMenuItem "Copy"提供低级功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com