简体   繁体   English

它可以在Eclipse中正常运行,但不能作为.jar文件运行

[英]It runs OK in Eclipse but not able to run as .jar file

I am writing a math program. 我正在写一个数学程序。 Everything runs fine in Eclipse, but when I export them as .jar file. 在Eclipse中一切正常,但是当我将它们导出为.jar文件时。 It did not run. 它没有运行。 When I double clicked on the .jar file, nothing happened. 当我双击.jar文件时,没有任何反应。 Here is a screenshot of my directory. 这是我的目录的屏幕截图。 Please help. 请帮忙。

Here are steps to export .jar file: 以下是导出.jar文件的步骤:

File->Export->JAR file(under java), click Next. File-> Export-> JAR文件(在Java下),单击Next。 In the JAR File Specification, select "TestingMath", and then select: Export all output folders for checked projects. 在JAR文件规范中,选择“ TestingMath”,然后选择:导出选中项目的所有输出文件夹。 Export Java source files and resources. 导出Java源文件和资源。 Export refactorings for checked projects. 导出检查项目的重构。
Browse to Desktop for destination. 浏览到桌面作为目的地。
Then click finish. 然后单击完成。

屏幕截图

package math;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;

public class Testing extends JFrame implements ActionListener
{
/**
* 
*/
private static final long serialVersionUID = 1L;
JLabel lblQuestion;
JLabel lblImage;
JButton bOK;
JButton bExit;
JPanel radioPanel;
JPanel panBottom;
JRadioButton[] radioButton;
String [] store ;
ButtonGroup bg;
JButton bNext;
JPanel mainPanel;
JPanel pRight;
JLabel lblCorrect;
JLabel lblWrong;
int vCorrect = 0;
int vWrong = 0;
JScrollPane scroll;

public Testing()
{
//mc = mathCombine;
//mc.setVisible(false);
mainPanel = new JPanel(new BorderLayout());
buildingGUI();
//listAllFiles();
innitializeAllComponents();        
URL url = getClass().getClassLoader().getResource("files/" + 1 + ".txt");

String strQuestion = readTextFile(url.toString(), 1);

store = strQuestion.toString().split("!!!");
lblQuestion.setText("<html>" + store[0] + "</html>");
//I need to get the image and display at the center according
//to the fileNumber
getTheImageAndDisplay(1);
assignRandomNumberToRadioButton(store[1]);
mainPanel.add(lblQuestion, BorderLayout.NORTH);
mainPanel.add(radioPanel, BorderLayout.WEST);
mainPanel.add(panBottom, BorderLayout.SOUTH);
mainPanel.add(scroll, BorderLayout.CENTER);
mainPanel.setPreferredSize(new Dimension(640, 480));

this.getContentPane().add(mainPanel);
}

private void getTheImageAndDisplay(int fileNumber) 
{
// TODO Auto-generated method stub
System.out.println("fileNumber for ismage: " + fileNumber);
lblImage.setIcon(new ImageIcon(Testing.class.getResource("/images/" + fileNumber + ".png"))); 
//scroll = new JScrollPane(lblImage);
}

private void assignRandomNumberToRadioButton(String sAnswer) 
{
// TODO Auto-generated method stub
int number  = Integer.parseInt(sAnswer.toString().trim());
//System.out.println("number: " + number);
Random random = new Random();
int rand = random.nextInt(4); //This is the number of radioButton.
//System.out.println("rand is: " + rand);
System.out.println("Answer issss: " + sAnswer);
radioButton[rand].setText(sAnswer);

if(!radioButton[0].getText().equals(""))
{
radioButton[1].setText("" +( number + 2));
radioButton[2].setText("" + (number - 2));
radioButton[3].setText("" + (number + 1));
}
else if(!radioButton[1].getText().equals(""))
{
radioButton[0].setText("" +( number + 2));
radioButton[2].setText("" + (number - 2));
radioButton[3].setText("" + (number + 1));
}
else if(!radioButton[2].getText().equals(""))
{
radioButton[1].setText("" +( number + 2));
radioButton[0].setText("" + (number - 2));
radioButton[3].setText("" + (number + 1));
}
else if(!radioButton[3].getText().equals(""))
{
radioButton[1].setText("" +( number + 2));
radioButton[2].setText("" + (number - 2));
radioButton[0].setText("" + (number + 1));
}        
}

/**
* Construct GUI.
*/
private void buildingGUI() 
{
lblImage = new JLabel();
lblImage.setHorizontalAlignment(JLabel.CENTER);
scroll = new JScrollPane(lblImage);
bNext = new JButton("Next");
lblQuestion = new JLabel();
bOK = new JButton("OK");
bExit = new JButton("Exit");
lblQuestion.setFont(new Font("Tahoma", Font.PLAIN, 12));
radioPanel = new JPanel();
panBottom = new JPanel();
panBottom.setLayout(new GridLayout(1, 2));
panBottom.add(bOK);
panBottom.add(bExit);
bg = new ButtonGroup();
radioPanel.setLayout(new GridLayout(4, 1));
radioButton = new JRadioButton[4];
radioButton[0] = new JRadioButton();
radioButton[1] = new JRadioButton();
radioButton[2] = new JRadioButton();
radioButton[3] = new JRadioButton();
radioPanel.setLayout(new GridLayout(10, 1));
radioPanel.add(radioButton[0]);
radioPanel.add(radioButton[1]);
radioPanel.add(radioButton[2]);
radioPanel.add(radioButton[3]);
radioPanel.add(new JLabel());
radioPanel.add(new JLabel());
radioPanel.add(new JLabel());
radioPanel.add(bNext);
radioPanel.add(new JLabel());
radioPanel.add(new JLabel());
bg.add(radioButton[0]);
bg.add(radioButton[1]);
bg.add(radioButton[2]);
bg.add(radioButton[3]);
pRight = new JPanel();
pRight.setLayout(new GridLayout(5, 2));
lblCorrect = new JLabel();        
pRight.add(lblCorrect);
lblWrong = new JLabel();        
pRight.add(lblWrong);
pRight.add(new JLabel("                   "));
pRight.add(new JLabel("                   "));
mainPanel.add(pRight, BorderLayout.EAST);    
}

private int generateRandomNumber()
{
// TODO Auto-generated method stub
Random random = new Random();
int rand = random.nextInt(20);  //This is the number of Files in the system.
return rand;
}

private void innitializeAllComponents() 
{
// TODO Auto-generated method stub
CompoundBorder border;
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
border = BorderFactory.createCompoundBorder( raisedbevel, loweredbevel);
lblQuestion.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblQuestion.setBorder(BorderFactory.createLineBorder(Color.GREEN));
lblQuestion.setBorder(border);
radioPanel.setBorder(border);
pRight.setBorder(border);
panBottom.setBorder(border);
radioButton[0].setFont(new Font("Tahoma", Font.BOLD, 16));
radioButton[1].setFont(new Font("Tahoma", Font.BOLD, 16));
radioButton[2].setFont(new Font("Tahoma", Font.BOLD, 16));
radioButton[3].setFont(new Font("Tahoma", Font.BOLD, 16));
lblCorrect.setFont(new Font("Tahoma", Font.BOLD, 14));
lblCorrect.setForeground(Color.BLUE);
lblCorrect.setHorizontalAlignment(JLabel.CENTER);
lblWrong.setFont(new Font("Tahoma", Font.BOLD, 14));
lblWrong.setForeground(Color.red);
lblWrong.setHorizontalAlignment(JLabel.CENTER);
bNext.addActionListener(this);
}
@SuppressWarnings("resource")
private String readTextFile(String fileName, int fileNumber) 
{
// TODO Auto-generated method stub
StringBuilder  stringBuilder = new StringBuilder();
BufferedReader reader = null;        
try
{
Random random = new Random();
//int rand = random.nextInt(20);
URL url = getClass().getClassLoader().getResource("files/" + fileNumber + ".txt");
File file = new File(url.toURI());
try
{
reader = new BufferedReader(new FileReader(file));
String line = null;
stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try
{
while(( line = reader.readLine()) != null ) 
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
} 
catch(IOException e)
{
e.printStackTrace();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
return stringBuilder.toString();
}

@Override
public void actionPerformed(ActionEvent ae) 
{
// TODO Auto-generated method stub
if(ae.getSource().equals(bNext))
{
//if nothing selected, display a message, 
//else: get the answer and display.
if(!radioButton[0].isSelected() && !radioButton[1].isSelected() && 
!radioButton[2].isSelected() && !radioButton[3].isSelected())
{
JOptionPane.showMessageDialog(this,"Please select an Answer.", "Nothing selected", 
JOptionPane.OK_OPTION);
return;
}
else //when user select an answer.
{
String strAnswer = "";
if(radioButton[0].isSelected())
{
strAnswer = radioButton[0].getText().trim();
}
else if(radioButton[1].isSelected())
{
strAnswer = radioButton[1].getText().trim();
}
else if(radioButton[2].isSelected())
{
strAnswer = radioButton[2].getText().trim();
}
else if(radioButton[3].isSelected())
{
strAnswer = radioButton[3].getText().trim();
}
if(strAnswer.equals(store[1].trim()))
{
String strCorrect = lblCorrect.getText();
if(strCorrect.equals(""))
{
strCorrect = "0";
}
vCorrect = Integer.parseInt(strCorrect);
vCorrect = vCorrect + 1;
lblCorrect.setText("" + vCorrect);
playSound("correct");
}
else
{
String strWrong = lblWrong.getText();
if(strWrong.equals(""))
{
strWrong = "0";
}
vWrong = Integer.parseInt(strWrong);
vWrong = vWrong + 1;
lblWrong.setText("" + vWrong);
playSound("wrong");
}
int fileNumber = generateRandomNumber();
URL url = null;
String file = "files/" + fileNumber + ".txt";
url = this.getClass().getClassLoader().getResource(file);
String strQuestion = readTextFile(url.toString(), fileNumber);
store = strQuestion.toString().split("!!!");
lblQuestion.setText("<html>" + store[0] + "</html>");
clearTextInAllRadioButtons();
assignRandomNumberToRadioButton(store[1]);
getTheImageAndDisplay(fileNumber);
}
}
}    

private void playSound(String sound) 
{
// TODO Auto-generated method stub
try 
{
URL url = null;
if(sound.equals("correct"))
{
url = this.getClass().getClassLoader().getResource("sound/ding.wav");
}
else if(sound.equals("wrong"))
{
url = this.getClass().getClassLoader().getResource("sound/buzz.wav");
}
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} 
catch (UnsupportedAudioFileException e) 
{
e.printStackTrace();
} 
catch (IOException e) 
{
e.printStackTrace();
} 
catch (LineUnavailableException e) 
{
e.printStackTrace();
}
}

private void clearTextInAllRadioButtons() 
{
// TODO Auto-generated method stub
radioButton[0].setText("");
radioButton[1].setText("");
radioButton[2].setText("");
radioButton[3].setText("");
bg.clearSelection();
}    
public static void main(String[] s)
{
Testing mr = new Testing();
mr.pack();
mr.setVisible(true);
}
}

Create a META-INF/MANIFEST.MF file in the jar. 在jar中创建一个META-INF/MANIFEST.MF文件。 Add the following entry to it: 向其中添加以下条目:

Main-Class: your.main.Class

You can add this folder and file to the project, so it will be added to the jar automatically. 您可以将此文件夹和文件添加到项目中,因此它将自动添加到jar中。

You can run it from a console or a cmd window to see what's wrong. 您可以从控制台或cmd窗口运行它,看看有什么问题。

if you are on windows, open a cmd window, then execute: 如果您在Windows上,请打开一个cmd窗口,然后执行:

java -jar /path/to/the/jar.jar

This way, it should output some errors or exceptions, and make everything easier. 这样,它应该输出一些错误或异常,并使一切变得容易。

I hope you find this usesful. 希望您会觉得有用。 :) :)


If you get a class not found error or something like that, you should do what the above answers suggest, creating a MANIFEST.MF and adding your main class. 如果遇到未找到类的错误或类似的错误,则应执行上述答案所建议的操作,创建一个MANIFEST.MF并添加您的主类。

I know it is late but the problem is with the resources you use in Eclipse for example if you have an image named (Image1.png ) and you can it in eclipse with getResource(....."image.png" ) one single letter can cause the problem and jar not run.But in eclipse it will run without any problem.So check the names of resources you use and also something other use(/) i have faced the same problem because of a sigle(/) i had(//)!! 我知道已经晚了,但是问题出在您在Eclipse中使用的资源 ,例如,如果您有一个名为(Image1.png )的图像,并且可以使用getResource(.....“ image.png” )在eclipse中使用它单个字母会导致问题并且jar无法运行。但是在eclipse中它将运行没有任何问题。因此请检查您使用的资源的名称以及其他用途(/),由于sigle(/)我也遇到了相同的问题我有(//)!!

Here must be the problem 这一定是问题所在

 URL url = getClass().getClassLoader().getResource("files/" + 1 + ".txt");

Missing a single(/) 缺少一个(/)

 URL url = getClass().getClassLoader().getResource("/files/" + 1 + ".txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM