简体   繁体   中英

ClassNotFoundException even though the class is properly defined (I think)

There is a similar question posted here but the answer seems to have never been found. I have tried a clean and am still getting a ClassNotFoundException .

So what is happening, like in the linked question, I call the add function in ArrayList<Player> and it proceeds to tell me that it cannot find the Player class, even though it is there and I have imported it correctly (since it can make use of the other class in that path. I will try and post as much code as I think necessary.

au.thewebeditor.scoreboard.apps.AccessMySQL.java

package au.thewebeditor.scoreboard.apps;

import java.sql.*;

import au.thewebeditor.scoreboard.defs.*;

public class AccessMySQL {
    private static Connection connection = null;
    private static Statement statement = null;
    private static PreparedStatement preparedStatement = null;
    private static ResultSet resultSet = null;

    public static void readData() throws SQLException, ClassNotFoundException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://HOSTNAME/socmedi2_rce?user=socmedi2_sam&password=abc123");
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM scores WHERE hasChanged > 0");
            writeResultSet(resultSet);
            //resetHasChanged();
        } catch (SQLException exc) {
            throw exc;
        } finally {
            close();
        }
    }   
    private static void writeResultSet(ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int score = resultSet.getInt("score");
            int lastScore = resultSet.getInt("lastScore");
            if (lastScore == 0){
                Scoreboard.addScore(id, name, score);
            } else {
                for (int i = 0; i < Scoreboard.getLength(); i++){
                    if (Scoreboard.getID(i) == id){
                        Scoreboard.updateScore(i, score);
                    }
                }
            }
        }
        Scoreboard.sortScoreboard();
    }
    private static void resetHasChanged() throws SQLException{
        preparedStatement = connection.prepareStatement("UPDATE scoreboard.scores SET hasChanged = 0 WHERE hasChanged > 0");
        preparedStatement.executeUpdate();
    }
    private static void close() {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (statement != null) {
                statement.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            //DO NOTHING???
        }
    }
}

au.thewebeditor.scoreboard.apps.Scorboard.java

package au.thewebeditor.scoreboard.apps;

import java.awt.*;
import java.awt.geom.*;
import java.sql.SQLException;
import java.util.*;

import javax.swing.*;

import au.thewebeditor.scoreboard.defs.*;

public class Scoreboard extends JWindow {
    static Config configuration = new Config();
    private static ArrayList<Player> scores = new ArrayList<Player>(20);
    private static JLabel titleLabel = new JLabel();
    private static JLabel subtitleLabel = new JLabel();
    private static JLabel[] positionLabel = new JLabel[configuration.getListLength()];
    private static JLabel[] nameLabel = new JLabel[configuration.getListLength()];
    private static JLabel[] scoreLabel = new JLabel[configuration.getListLength()];
    private static JLabel[] changeLabel = new JLabel[configuration.getListLength()];
    private static JLabel[] arrowLabel = new JLabel[configuration.getListLength()];

    public Scoreboard(){
        //Set to full screen
        this.setBounds(0, 0, Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
        updateLabels(); //Set value of headings
        updateScores();
        this.getContentPane().setBackground(Color.white);
        GridBagLayout mainLayout = new GridBagLayout();
        setLayout(mainLayout);//Grid size is 5 across: Position, name, $value, change, arrow
        //TITLE LABEL
        GridBagConstraints constraint = AutoConstraint.buildConstraint(new AutoConstraint(0, 0, 5, 1, 100, 0, GridBagConstraints.CENTER));
        mainLayout.setConstraints(titleLabel, constraint);
        add(titleLabel);
        //SUBTITLE LABEL
        constraint = AutoConstraint.buildConstraint(new AutoConstraint(0, 1, 5, 1, 100, 0, GridBagConstraints.CENTER));
        mainLayout.setConstraints(subtitleLabel, constraint);
        add(subtitleLabel);
        //SCOREBOARD
        for (int i = 0; i < configuration.getListLength(); i++){
            if (nameLabel[i].getText() == ""){
                //Print empty line
                constraint = AutoConstraint.buildConstraint(new AutoConstraint(1, i + 2, 5, 1, 100, 1, GridBagConstraints.WEST));
                mainLayout.setConstraints(nameLabel[i], constraint);
                add(nameLabel[i]);
            } else {
                add(arrowLabel[i]);
                //ChangeLabel
                constraint = AutoConstraint.buildConstraint(new AutoConstraint(0, i + 2, 1, 1, 20, 1, GridBagConstraints.EAST));
                mainLayout.setConstraints(changeLabel[i], constraint);
                add(changeLabel[i]);
                //ArrowLabel
                constraint = AutoConstraint.buildConstraint(new AutoConstraint(1, i + 2, 1, 1, 5, 1, GridBagConstraints.WEST));
                mainLayout.setConstraints(arrowLabel[i], constraint);
                add(arrowLabel[i]);
                //PositionLabel
                constraint = AutoConstraint.buildConstraint(new AutoConstraint(2, i + 2, 1, 1, 5, 1, GridBagConstraints.EAST));
                mainLayout.setConstraints(positionLabel[i], constraint);
                add(positionLabel[i]);
                //NameLabel
                constraint = AutoConstraint.buildConstraint(new AutoConstraint(3, i + 2, 1, 1, 40, 1, GridBagConstraints.WEST));
                mainLayout.setConstraints(nameLabel[i], constraint);
                add(nameLabel[i]);
                //ScoreLabel
                constraint = AutoConstraint.buildConstraint(new AutoConstraint(4, i + 2, 1, 1, 30, 1, GridBagConstraints.WEST));
                mainLayout.setConstraints(scoreLabel[i], constraint);
                add(scoreLabel[i]);
            }
        }
        this.setBounds(0, 0, Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
        setVisible(true);
    }

    public static void updateLabels() {//Updates heading labels
        titleLabel.setText(configuration.getTitle());
        subtitleLabel.setText(configuration.getSubtitle());
        titleLabel.setFont(new Font("Segoe UI", Font.BOLD, (int)(42*configuration.getFontAdjust())));
        subtitleLabel.setFont(new Font("Segoe UI", Font.BOLD, (int)(32*configuration.getFontAdjust())));
    }
    public static void updateScores() {//Updates scoreboard labels
        try {
            AccessMySQL.readData();
        } catch (SQLException e) {
            String[] options = {"Retry", "Exit"};
            int response = JOptionPane.showOptionDialog(null, "MySQL database failed to load. Error code: " + Integer.toString(e.getErrorCode()) + ".\n" + e.getMessage(), "MySQL Error", 0, JOptionPane.ERROR_MESSAGE, null, options, options[1]);
            if (response == 1 || response == JOptionPane.CLOSED_OPTION)
                Runtime.getRuntime().exit(ERROR);
            else
                Program.redrawScoreboard();
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(null, "Hard Coded Failure, Contact Mowgli for Support.", "Error", JOptionPane.ERROR_MESSAGE);
            Runtime.getRuntime().exit(ERROR);
        }
        int change = 0;
        for (int i = 0; i < configuration.getListLength(); i++){
            try {
                positionLabel[i] = new JLabel(Integer.toString(i + 1) + ". ");
                positionLabel[i].setFont(new Font("Segoe UI", Font.PLAIN, (int)(24*configuration.getFontAdjust())));
                nameLabel[i] = new JLabel(scores.get(i).getName());
                nameLabel[i].setFont(new Font("Segoe UI", Font.BOLD, (int)(24*configuration.getFontAdjust())));
                scoreLabel[i] = new JLabel("$" + Integer.toString(scores.get(i).getScore()));
                scoreLabel[i].setFont(new Font("Segoe UI", Font.PLAIN, (int)(24*configuration.getFontAdjust())));
                change = scores.get(i).getLastPosition() - i - 1;
                changeLabel[i] = new JLabel();
                changeLabel[i].setFont(new Font("Segoe UI", Font.BOLD, (int)(24*configuration.getFontAdjust())));
                if (scores.get(i).getLastPosition() == 0){
                    changeLabel[i].setText("NEW! ");
                    changeLabel[i].setForeground(Color.yellow);
                    arrowLabel[i] = new JLabel(" " + Character.toString((char)171));
                    arrowLabel[i].setForeground(Color.yellow);
                } else if (change > 0){
                    changeLabel[i].setText("+" + Integer.toString(change) + " ");
                    changeLabel[i].setForeground(Color.green);
                    arrowLabel[i] = new JLabel(" " + Character.toString((char)233));
                    arrowLabel[i].setForeground(Color.green);
                } else if (change < 0){
                    changeLabel[i].setText(Integer.toString(change) + " ");
                    changeLabel[i].setForeground(Color.red);
                    arrowLabel[i] = new JLabel(" " + Character.toString((char)234));
                    arrowLabel[i].setForeground(Color.red);
                } else {
                    changeLabel[i].setText(Character.toString((char)177)+"0 ");
                    changeLabel[i].setForeground(Color.gray);
                    arrowLabel[i] = new JLabel(" " + Character.toString((char)108));
                    arrowLabel[i].setForeground(Color.gray);
                }
                scores.get(i).setLastPosition(i+1); //Sets last position before sort is called.
                arrowLabel[i].setFont(new Font("Wingdings", Font.PLAIN, (int)(24*configuration.getFontAdjust())));
            } catch (IndexOutOfBoundsException e) {
                nameLabel[i] = new JLabel("");
            }
        }
    }
        public static void addScore(int id, String name, int score){//Adds new score to scores ArrayList
            scores.add(new Player(id, name, score, 0));
        }
    public static void updateScore(int index, int score){//Updates score value, does not rearrange or assign lastPosition or position
        scores.get(index).setScore(score);
    }
    public static int getLength(){//Returns the current length of the scoreboard
        return scores.size();
    }
    public static int getID(int index){//takes the ArrayList index value and returns the ID value
        return scores.get(index).getID();
    }
    public static void sortScoreboard(){//Sorts scoreboard DESC
        Collections.sort(scores);
    }
}

au.thewebeditor.scoreboard.apps.Program.java

package au.thewebeditor.scoreboard.apps;

   public class Program {
    private static Scoreboard sb;
    private static ConfigPanel cp;

public Program(){
    sb = new Scoreboard();
    cp = new ConfigPanel();
}

public static void redrawScoreboard() throws NullPointerException{
    try{
        sb.dispose();
    } catch (NullPointerException e){
        //DO NOTHING
    }
    sb = new Scoreboard();
    cp.toFront();
}

public static void showConfig(){
    cp.setVisible(true);
    cp.toFront();
}

public static void main(String[] arguments){
    new Program();
}
}

I hope this is enough informmation to spot the error. Any help would be greatly appreciated. Including proper coding habits, as I am new to Java.

You use Eclipse. This is kind of vague, but from what we know my advices: Right click on the project in the Project Explorer, then click Properties (bottom of the context menu). In the upcoming Properties dialog's left-side tree-view select "Java Build Path", this is your friend. You can see which Libraries are included, what are the library and project dependencies. You can set the order of export and imports, check what sources are included, etc.

Also you can check the "Java Compiler" tree node in the Properties dialog. You can see and change your Java compatibility level, which JDK provides the JVM for you, other settings which can be important too.

The main cause is that probably the not found classes are not in the classpath. Since it comes from your own source code, check what source folders are included in the dialog I guided you on the ("Source" tab).

Check that your project has the desired layout, the packages are in place. Is this a project you imported from somewhere else?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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