gpt4 book ai didi

java - 使用 Swing GUI 在一个类中执行程序

转载 作者:行者123 更新时间:2023-12-02 04:05:32 27 4
gpt4 key购买 nike

我有一个程序可以比较然后合并两个文件并创建一个新文件。我现在正在尝试使用 Swing 编写一个可以与该程序交互的 GUI。到目前为止,一切似乎都已就位,但是当我尝试运行该程序时,我收到大量 Swing 和 awt 错误。下面是我尝试运行的程序。

/*
* 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 HelloCKL;

import java.util.ArrayList;
import java.io.*;


public class HelloCKL {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
String sourceFile1Path = helloSwingCKL.fileSource;
String sourceFile2Path = helloSwingCKL.fileToAppend;

String mergedFilePath = "merged_test2.ckl";

File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);

File mergedFile = new File(mergedFilePath);

mergeFiles(files, mergedFile);
}


public static void mergeFiles(File[] files, File mergedFile) {
// NEW
ArrayList<String> list = new ArrayList<String>();

FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}

// Going in a different direction. We are using a couple booleans to tell us when we want to copy or not. So at the beginning since we start
// with our source file we set copy to true, we want to copy everything and insert vuln names into our list as we go. After that first file
// we set the boolean to false so that we dont start copying anything from the second file until it is a vuln. We set to true when we see vuln
// and set it to false if we already have that in our list.
// We have a tmpCopy to store away the value of copy when we see a vuln, and reset it to that value when we see an </VULN>
Boolean copy = true;
Boolean tmpCopy = true;
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));

String aLine;
while ((aLine = in.readLine()) != null) {
// Skip the close checklist and we can write it in at the end
if (aLine.trim().equals("</CHECKLIST>")){
continue;
}
if (aLine.trim().equals("<VULN>")){
// Store our current value of copy
tmpCopy = copy;
copy = true;

String aLine2 = in.readLine();
String aLine3 = in.readLine();
String nameLine = in.readLine();

if(list.contains(nameLine.trim())){
System.out.println("Skipping: " + nameLine);
copy = false;
// while (!(aLine.trim().equals("</VULN>"))){
// aLine = in.readLine();
// }
// continue; // this would skip the writing out to file part
}
else{
list.add(nameLine.trim());
System.out.println("::: List is now :::" );
System.out.println(list.toString());
}
if(copy){
out.write(aLine);
out.newLine();
out.write(aLine2);
out.newLine();
out.write(aLine3);
out.newLine();
out.write(nameLine);
out.newLine();
}
}
else{
if(copy){
out.write(aLine);
out.newLine();
}
}
// after we have written to file, if the line was a close vuln, switch copy back to original value
if (aLine.trim().equals("</VULN>")){
copy = tmpCopy;
}
}

in.close();
} catch (IOException e) {
e.printStackTrace();
}
copy = false;
}

// Now lets add the close checklist tag we omitted before
try{
out.write("</CHECKLIST>");
} catch (IOException e){
e.printStackTrace();
}

try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

这是我正在使用的 Swing 编码。

/*
* 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 hellockl;

import static HelloCKL.HelloCKL.mergeFiles;
import java.io.File;
import javax.swing.JFileChooser;
import java.util.ArrayList;
import java.io.*;


public class helloSwingCKL extends javax.swing.JFrame {

/**
* Creates new form helloSwingCKL
*/
public helloSwingCKL() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jButton3 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(java.awt.Color.lightGray);

jButton1.setText("Source");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setText("New .ckl");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});

jTextField3.setText("Save merged file as...");

jButton3.setText("Merge");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jTextField3)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(104, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File source = chooser.getSelectedFile();
String fileSource = source.getAbsolutePath();
jTextField1.setText(fileSource);
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File toAppend = chooser.getSelectedFile();
String fileToAppend = toAppend.getAbsolutePath();
jTextField2.setText(fileToAppend);
}

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
HelloCKL.mergeFiles();
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(helloSwingCKL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new helloSwingCKL().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}

以下是“大量错误”...

*run:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: hellockl.HelloCKL.main
at hellockl.helloSwingCKL.jButton3ActionPerformed(helloSwingCKL.java:145)
at hellockl.helloSwingCKL.access$300(helloSwingCKL.java:18)
at hellockl.helloSwingCKL$4.actionPerformed(helloSwingCKL.java:73)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 15 seconds)*

下面是编译器错误。

 Compiling 1 source file to C:\Users\blakey\Documents\NetBeansProjects\helloCKL\build\classes
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\helloSwingCKL.java:3: error: package HelloCKL does not exist
import static HelloCKL.HelloCKL.mergeFiles;
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\helloSwingCKL.java:3: error: static import only from classes and interfaces
import static HelloCKL.HelloCKL.mergeFiles;
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\helloSwingCKL.java:129: error: cannot access HelloCKL
HelloCKL.main();
bad source file: C:\Users\blakey\Documents\NetBeansProjects\helloCKL\src\hellockl\HelloCKL.java
file does not contain class hellockl.HelloCKL
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
3 errors
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\nbproject\build-impl.xml:952: The following error occurred while executing this line:
C:\Users\blakey\Documents\NetBeansProjects\helloCKL\nbproject\build-impl.xml:269: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)

最佳答案

when I attempt to run the program I get a ton of Swing and awt errors

您似乎正在尝试运行无法编译的代码永远不要这样做 - 在尝试运行程序之前首先修复所有编译错误,如果您无法弄清楚如何做到这一点并需要帮助,那么至少将编译错误与您的问题一起发布在此处,因为“大量错误”并不能告诉我们太多可以处理的信息。

快速查看代码的主要问题是您错误地调用了 mergeFiles(...) 方法。您在不传递任何参数的情况下调用它:

HelloCKL.mergeFiles();

并且它已被写入需要两个参数:

public static void mergeFiles(File[] files, File mergedFile) {

解决方案:就像在原始 main 方法中尝试调用该方法一样,通过传入要合并的文件数组以及要合并的最终结果文件来调用该方法。看起来您还有其他代码试图获取这些文件,但似乎没有对它获得的结果执行任何操作,而您应该使用它。

关于java - 使用 Swing GUI 在一个类中执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34317782/

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