我有两个用于io /读取文件的一个类和一个用于GUI的一个,在过去的几天里我正在研究io /阅读的类,我使用简单的技术通过写入从硬盘获取文件文件名只作为字符串注释:查看代码,但现在我完成io /阅读代码后,我需要通过在Gui类中添加JFileChooser
来使用更专业的方式并将它们结合起来,这里的难度可以有人告诉我怎么样?
GUI类中限制器内的Jfilechooser
代码,只打开JFileChooser
并选择文件并将文件保存到String srtPath
。
Action openAction = new AbstractAction("Open Subtitle", openIcon) {
@Override
public void actionPerformed(ActionEvent e) {
ourFileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
ourFileSelector.showSaveDialog(null);
ourSrtFile = ourFileSelector.getSelectedFile();
srtPath = ourSrtFile.getAbsolutePath();
}
};
所有类阅读文件
package AnimeAid;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadFile {
public static ArrayList<String> getFileStartingTime(String file){
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
Lines.add(line.substring(0, 12));
}
}
}catch(IOException ex){
System.err.println(ex);
}
return Lines;
}
public static ArrayList<String> getFileEndingTime(String file){
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
Lines.add(line.substring(18, 29));
}
}
}catch(IOException ex){
System.err.println(ex);
}
return Lines;
}
public static ArrayList<String> readSubtitles(String file)
{
ArrayList<String> Lines = new ArrayList<String>();
try{
//String file = "tra.srt";
Charset charset = Charset.defaultCharset();
Path path = Paths.get(file);
byte[] encoded = Files.readAllBytes(path);
String data = charset.decode(ByteBuffer.wrap(encoded)).toString();
Pattern p = Pattern.compile("(\\d+:\\d+:\\d+,\\d+) --> (\\d+:\\d+:\\d+,\\d+)\\s*(.*?)\\s*(^$|\\Z)", Pattern.DOTALL | Pattern.MULTILINE);
Matcher m = p.matcher(data);
while (m.find()){
//String startTime = m.group(1);
//String endTime = m.group(2);
//String subtitle = m.group(3);
Lines.add(m.group(3));
//System.out.println(startTime);
//System.out.println(endTime);
}
}catch(IOException ex){
System.err.println(ex);
}
return Lines;
}
public static ArrayList<String> ArraylineLengths(String file) {
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
line = line.replace("\uFEFF", "");
if(isInteger(line)) {
int i = Integer.parseInt(line);
if(i > 0) {
Lines.add(line);
}
}
}
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch(IOException e) {
// do nothing
}
}
}
return (Lines);
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
public static int maxLine(String file){
try
{
//String file = "tra.srt";
int max = 0;
BufferedReader br = null;
try { br = new BufferedReader(new FileReader(file)); }
catch (FileNotFoundException e) { System.out.println(e); }
String line;
while((line = br.readLine()) != null)
{
if (isInteger(line))
{
max++;
}
}
return max+1;
}
catch( NumberFormatException | IOException ex) {ex.printStackTrace();}
return 0;
}
}
答案应该是这样的
String file = GuiInterface.srtPath;
我试过这个
public class ReadFile {
GuiInterface tt = new GuiInterface(null);
public static String file = GuiInterface.srtPath;
public static ArrayList<String> getFileStartingTime(){
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
Lines.add(line.substring(0, 12));
}
}
}catch(IOException ex){
System.err.println(ex);
}
return Lines;
}
但是当我使用这个vlcj库时,只显示视频。
这是我向Jtable添加数据的方法
/*
* 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 AnimeAid;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.BorderFactory.*;
import javax.swing.border.*;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
/**
*
* @author isslam
*/
public class GuiInterface extends JFrame {
JComboBox laList;
ReadFile reader;
private final int numberOfButton = 6;
private final JTable table;
JToolBar toolBar;
private final JTextField enterText,startTime,endTime;
private final JMenu jMenu1,jMenu2,jMenu3;
private final JMenuBar jMenuBar1;
private final JMenuItem itemNewSrt,itemOpenVideo,itemSavefile;
private static JFileChooser ourFileSelector,ourVideoSelector;
File ourVideoFile,ourSrtFile;
Border Campound,empty,Boveld,etch;
private final JLabel startTimeingLable,endTimeingLabel;
public static String mediaPath="",srtPath="";
Canvas c;
ImageIcon[] icon;
JButton[] Obutton;
static final int COLUMN = 4 ;
public static void main(String[] args) throws IOException
{
//ReadFile.readSubtitles();
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GuiInterface("");
}
});
}
public GuiInterface(String title){
//reader = new ReadFile();
setSize(1024, 720);
setVisible(true);
setTitle("AnimeFactor");
setDefaultCloseOperation(GuiInterface.EXIT_ON_CLOSE);
//video setting
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
c = new Canvas();
String[] petStrings = { "Translation Line", "Both Line" };
laList = new JComboBox(petStrings);
c.setBackground(Color.black);
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(c, BorderLayout.CENTER);
add(p, BorderLayout.CENTER);
EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(c));
mediaPlayer.playMedia("C:\\Users\\isslam\\Downloads\\gg.mp4");
/* String[] columnNames = {"#","Start","End","Translation column"};
Object[][] data = new Object [ReadFile.maxLine(srtPath)][COLUMN];
ArrayList <String > Dumy = new ArrayList<String>();
//String [] countries = list.toArray(new String[list.size()]);
Dumy = ReadFile.ArraylineLengths(srtPath);
for(int i = 0; i < Dumy.size(); i++)
{
data[i][0] = Dumy.get(i);
}
ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
for(int i=0;i < ReadFile.maxLine(srtPath);i++){
// data[i][0] = ReadFile.lineLengths();
data[i][1] = starts.get(i) ;
data[i][2] = ends.get(i);
data[i][3] = subs.get(i);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
*/
ImageIcon openIcon = new ImageIcon(
GuiInterface.class.getResource("/resources/image/folder-icon.png"));
ImageIcon saveIcon = new ImageIcon(
GuiInterface.class.getResource("/resources/image/red-disk-icon.png"));
ImageIcon newIcon = new ImageIcon(
GuiInterface.class.getResource("/resources/image/Actionsnew-icon.png"));
Action saveAction = new AbstractAction("Save", saveIcon) {
@Override
public void actionPerformed(ActionEvent e) {
}
};
Action newAction = new AbstractAction("New", newIcon) {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("New File");
}
};
jMenu1 = new JMenu("File");
jMenu2 = new JMenu("Video");
jMenu3 = new JMenu("Subtitle");
itemNewSrt = new JMenuItem(newAction);
jMenu1.add(itemNewSrt);
itemSavefile = new JMenuItem(saveAction);
jMenu1.add(itemSavefile);
jMenuBar1 = new JMenuBar();
jMenuBar1.setBorder(etch);
setJMenuBar(jMenuBar1);
jMenuBar1.add(jMenu1);
jMenuBar1.add(jMenu2);
jMenuBar1.add(jMenu3);
table = new JTable();
table.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
TableColumn columnA = table.getColumn("#");
columnA.setMinWidth(10);
columnA.setMaxWidth(40);
TableColumn columnB= table.getColumn("Start");
columnB.setMinWidth(80);
columnB.setMaxWidth(90);
TableColumn columnC= table.getColumn("End");
columnC.setMinWidth(80);
columnC.setMaxWidth(90);
Obutton = new JButton[numberOfButton];
etch = BorderFactory.createEtchedBorder();
enterText = new JTextField();
enterText.setPreferredSize(new Dimension(0,100));
ourFileSelector = new JFileChooser();
startTime = new JTextField();
startTime.setPreferredSize(new Dimension(120, 20));
startTimeingLable = new JLabel("Starting Time");
endTimeingLabel = new JLabel("Ending Time");
endTime = new JTextField();
endTime.setPreferredSize(new Dimension(120, 20));
toolBar = new JToolBar();
//toolBar.add(Box.createHorizontalGlue());
toolBar.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
toolBar.add(newAction);
toolBar.add(saveAction);
JPanel toolBarPane = new JPanel(new BorderLayout());
toolBarPane.add(toolBar,BorderLayout.NORTH);
JPanel timing = new JPanel(new FlowLayout(FlowLayout.TRAILING));
timing.add(startTimeingLable);
timing.add(startTime);
timing.add(endTimeingLabel);
timing.add(endTime);
timing.add(laList);
empty = BorderFactory.createEmptyBorder(30, 5, 5, 5);
Boveld = BorderFactory.createBevelBorder(BevelBorder.RAISED);
Campound = BorderFactory.createCompoundBorder(empty,Boveld);
JPanel textFiled = new JPanel(new BorderLayout());
textFiled.add(timing);
textFiled.add(enterText,BorderLayout.SOUTH);
textFiled.setBorder(Campound);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.SOUTH);
add(textFiled, BorderLayout.EAST);
add(toolBarPane,BorderLayout.PAGE_START);
Action openAction = new AbstractAction("Open Subtitle", openIcon) {
@Override
public void actionPerformed(ActionEvent e) {
ourFileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
ourFileSelector.showSaveDialog(null);
ourSrtFile = ourFileSelector.getSelectedFile();
srtPath = ourSrtFile.getAbsolutePath();
DefaultTableModel model = createModel(srtPath);
table.setModel(model);
}
};
//Container cp = getContentPane();
toolBar.add(openAction);
itemOpenVideo = new JMenuItem(openAction);
jMenu1.add(itemOpenVideo);
itemOpenVideo.addActionListener(new MenuBarMethod());
}
private DefaultTableModel createModel(String srtPath) {
String[] columnNames = {"#", "Start", "End", "Translation column"};
int maxLine = ReadFile.maxLine(srtPath); // debug
//Object[][] data = new Object[maxLine][];
System.out.println(maxLine); // debug
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
for (int i = 0; i < ReadFile.maxLine(srtPath) - 1; i++) {
model.addRow(new Object[] {starts.get(i), ends.get(i), subs.get(i)});
}
return model;
}
public class MenuBarMethod implements ActionListener{
@Override
public void actionPerformed(ActionEvent a){
Object buttonPressed=a.getSource();
if(buttonPressed.equals(itemOpenVideo)){
ourVideoSelector.setFileSelectionMode(JFileChooser.FILES_ONLY);
ourVideoSelector.showSaveDialog(null);
ourVideoFile = ourVideoSelector.getSelectedFile();
mediaPath = ourVideoFile.getAbsolutePath();
}
}
}
}
代码的问题是这部分代码无法正常工作
table = new JTable();
table.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
TableColumn columnA = table.getColumn("#");
columnA.setMinWidth(10);
columnA.setMaxWidth(40);
TableColumn columnB= table.getColumn("Start");
columnB.setMinWidth(80);
columnB.setMaxWidth(90);
TableColumn columnC= table.getColumn("End");
columnC.setMinWidth(80);
columnC.setMaxWidth(90);
文件的一部分
1
00:00:01,600 --> 00:00:04,080
<b>Mr Magnussen, please state your
full name for the record.</b>
2
00:00:04,080 --> 00:00:07,040
Charles Augustus Magnussen.
现在这是应用程序的图片
当你看到打开要阅读的文件的图标不存在因为某些原因JTextFiled下的白色背景告诉jtable已创建但尚无信息
答案 0 :(得分:2)
&#34;答案应该是这样的&#34;
String file = GuiInterface.srtPath;
您的GuiInterface
是正在运行的课程。由于ReadFile
是使用static
方法的&#34;帮助程序类&#34; ,因此不应该对GuiInterface
知道任何事情。类。
您应该做的是让getFileStartingTime()
采用String path
参数,让FileReader
使用path
参数。
public static ArrayList<String> getFileStartingTime(String path) {
ArrayList<String> Lines = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path));
然后,您应该从ReadFile.getFileStartTime(...)
拨打Action
,并对返回的ArrayList
执行某些操作。像
File ourSrtFile = ourFileSelector.getSelectedFile();
String srtPath = ourSrtFile.getAbsolutePath();
ArrayList<String> array = ReadFile.getFileStartingTime(srtPath);
DefaultListModel model = (DefaultListModel) list.getModel();
for (String s : array) {
model.addElement(s);
}
这是一个完整的例子。但请注意:读取文件(以及长时间运行的任务)应该在后台线程中完成,可能使用SwingWorker,但我现在懒得这么做。你可以看看链接
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class GuiInterface {
private JFileChooser ourFileSelector = new JFileChooser();
private JList list = new JList(new DefaultListModel());
public GuiInterface() {
Action openAction = new AbstractAction("Open Subtitle") {
@Override
public void actionPerformed(ActionEvent e) {
ourFileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
ourFileSelector.showSaveDialog(null);
File ourSrtFile = ourFileSelector.getSelectedFile();
String srtPath = ourSrtFile.getAbsolutePath();
ArrayList<String> array = ReadFile.getFileStartingTime(srtPath);
DefaultListModel model = (DefaultListModel) list.getModel();
for (String s : array) {
model.addElement(s);
}
}
};
JButton button = new JButton(openAction);
JFrame frame = new JFrame();
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(200, 300));
frame.add(scroll);
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] aregs) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GuiInterface();
}
});
}
}
class ReadFile {
public static ArrayList<String> getFileStartingTime(String path) {
ArrayList<String> Lines = new ArrayList<String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
Lines.add(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
return Lines;
}
}
修改强>
立即尝试
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class GuiInterface {
private JFileChooser ourFileSelector = new JFileChooser();
private JTable table = new JTable();
public GuiInterface() {
Action openAction = new AbstractAction("Open Subtitle") {
@Override
public void actionPerformed(ActionEvent e) {
ourFileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
ourFileSelector.showSaveDialog(null);
File ourSrtFile = ourFileSelector.getSelectedFile();
String srtPath = ourSrtFile.getAbsolutePath();
DefaultTableModel model = createModel(srtPath);
table.setModel(model);
}
};
JButton button = new JButton(openAction);
JFrame frame = new JFrame();
JScrollPane scroll = new JScrollPane(table);
//scroll.setPreferredSize(new Dimension(200, 300));
frame.add(scroll);
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private DefaultTableModel createModel(String srtPath) {
String[] columnNames = {"#", "Start", "End", "Translation column"};
int maxLine = ReadFile.maxLine(srtPath); // debug
//Object[][] data = new Object[maxLine][];
System.out.println(maxLine); // debug
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
for (int i = 0; i < ReadFile.maxLine(srtPath) - 1; i++) {
model.addRow(new Object[] {starts.get(i), ends.get(i), subs.get(i)});
}
return model;
}
public static void main(String[] aregs) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GuiInterface();
}
});
}
}
class ReadFile {
public static ArrayList<String> getFileStartingTime(String file) {
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
Lines.add(line.substring(0, 12));
}
}
} catch (IOException ex) {
System.err.println(ex);
}
return Lines;
}
public static ArrayList<String> getFileEndingTime(String file) {
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf(':') != -1 && line.indexOf(',') != -1 && line.indexOf('0') != -1) {
Lines.add(line.substring(18, 29));
}
}
} catch (IOException ex) {
System.err.println(ex);
}
return Lines;
}
public static ArrayList<String> readSubtitles(String file) {
ArrayList<String> Lines = new ArrayList<String>();
try {
//String file = "tra.srt";
Charset charset = Charset.defaultCharset();
Path path = Paths.get(file);
byte[] encoded = Files.readAllBytes(path);
String data = charset.decode(ByteBuffer.wrap(encoded)).toString();
Pattern p = Pattern.compile("(\\d+:\\d+:\\d+,\\d+) --> (\\d+:\\d+:\\d+,\\d+)\\s*(.*?)\\s*(^$|\\Z)", Pattern.DOTALL | Pattern.MULTILINE);
Matcher m = p.matcher(data);
while (m.find()) {
//String startTime = m.group(1);
//String endTime = m.group(2);
//String subtitle = m.group(3);
Lines.add(m.group(3));
//System.out.println(startTime);
//System.out.println(endTime);
}
} catch (IOException ex) {
System.err.println(ex);
}
return Lines;
}
public static ArrayList<String> ArraylineLengths(String file) {
ArrayList<String> Lines = new ArrayList<String>();
//String file = "tra.srt";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace("\uFEFF", "");
if (isInteger(line)) {
int i = Integer.parseInt(line);
if (i > 0) {
Lines.add(line);
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// do nothing
}
}
}
return (Lines);
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
public static int maxLine(String file) {
try {
//String file = "tra.srt";
int max = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
System.out.println(e);
}
String line;
while ((line = br.readLine()) != null) {
if (isInteger(line)) {
max++;
}
}
return max + 1;
} catch (NumberFormatException | IOException ex) {
ex.printStackTrace();
}
return 0;
}
}