I'm learning Java and experimenting with Javafx in netbeans.
I am running the sqlite tutorial here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm
When set up as a lone-file it works fine of course.
I'm setting it up in a test project "testDB" and for some reason when I initiate the class the class itself is recognized, but main() is not running.
Here is the testdb file itself:
testDB.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 sqlitetest;
import java.sql.*;
/**
*
*/
public class testDB {
public static void main(String args[]) {
//THESE STEPS ARE ON NOT RUNNING (compiles without errors)
System.out.println("testing");
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
public void makeStuff(){
}
}
sqlitetest.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 sqlitetest;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
*/
public class Sqlitetest extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
testDB test = new testDB();
test.makeStuff();
launch(args);
}
}
I think you are getting confused between a constructor and a main method.
A main method is only invoked when you start the JVM, running that specific class (or if you invoke it explicitly elsewhere).
A constructor is invoked when you create an instance of the class, like you are doing here.
In testdb, change:
public static void main(String args[]) {
to
public testdb() {
Alternatively, invoke testdb.main(args) (or with some other parameter) in Sqlitetest.main.
Related
I am just a beginner trying to use a git java project, I have downloaded a java project from git and when I try to run the splash.java file it says:-
Class "Electricity.splash" does not have a main method
Here's the screenshot of the screen:-
Screenshot of my error
conn.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.
*/
/**
*
* #author Hp pc
*/
class conn {
}
screenshot of conn.java file in Electricity folder
screenshot
Here's my splash.java which has the main method:
package Electricity;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class splash {
public static void main(String[] args){
fframe f1 = new fframe();
f1.setVisible(true);
int i;
int x=1;
for(i=2; i<=600; i+=4, x+=1){
f1.setLocation(800 - ((i+x)/2), 500 - (i/2));
f1.setSize(i+x,i);
try{
Thread.sleep(10);
}catch(Exception e){}
}
}
}
class fframe extends JFrame implements Runnable{
Thread t1;
fframe(){
super("Electricity Billing System");
setLayout(new FlowLayout());
ImageIcon c1 = new ImageIcon(ClassLoader.getSystemResource("icon/elect.jpg"));
Image i1 = c1.getImage().getScaledInstance(730, 550,Image.SCALE_DEFAULT);
ImageIcon i2 = new ImageIcon(i1);
JLabel l1 = new JLabel(i2);
add(l1);
t1 = new Thread(this);
t1.start();
}
public void run(){
try{
Thread.sleep(7000);
this.setVisible(false);
Login l = new Login();
l.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
}
Please Guide me, is it because I haven't downloaded jdbc or something else?
First create your main method in the main class then, to specify the class with the main method: left click on the name of your project, properties, Run, and there specify the main class with the main method. In your capture: try, Import java.sql.Connection;
What I want: I have an editor plug-in for my custom DSL. I want to offer the user to set up a new DSL project with a project wizard. Normally these projects are Maven projects, so I want to provide setting up the project directly as a Maven project. To do that I want to extend the class MavenProjectWizardin the package org.eclipse.m2e.core.ui.internal.wizards.MavenProjectWizard and then add another wizard page with the details regarding the DSL project.
What I have: This is my try to do it at the moment:
/*
* Copyright (c) 2017 RWTH Aachen. All rights reserved.
*
* http://www.se-rwth.de/
*/
package de.se_rwth.transformationeditor.wizard;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.m2e.core.ui.internal.wizards.MavenProjectWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import jline.internal.Log;
/**
* Offers a wizard to create a new Transformation project
*
* #author (last commit) $Philipp Nolte$
* #version $Revision$, $12.1.2017$
* #since 0.0.3
*/
#SuppressWarnings("restriction")
public class CDProjectWizard extends MavenProjectWizard{
protected CDWizardPageOne one;
protected WizardPage currentPage;
private IWorkbench workbench;
public CDProjectWizard() {
super();
}
/**
* #see org.eclipse.jface.wizard.IWizard#addPages()
*/
#Override
public void addPages() {
one = new CDWizardPageOne();
addPage(one);
super.addPages();
}
/**
* #see org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard#init(org.eclipse.ui.IWorkbench,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
#Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
super.init(workbench, selection);
this.workbench = workbench;
}
/**
* #see org.eclipse.jface.wizard.IWizard#getWindowTitle()
*/
#Override
public String getWindowTitle() {
return "New Class Diagram Transformation Project";
}
/**
* Creates a new Transformation project with the project name given in the
* wizard. Inside this project a new folder named "Transformations" is
* created. If a project with the same name already exists, an error window is
* shown. In addition to that, checks if user wants to create CD or MA xample
* files and creates them if wanted.
*
* #see org.eclipse.jface.wizard.IWizard#performFinish()
*/
#Override
public boolean performFinish() {
if (this.canFinish()) {
// Create new project
String projectName = this.one.getProjectNameText();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(projectName);
try {
if (!project.exists()) {
project.create(null);
}
else {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
MessageDialog.openError(this.workbench.getActiveWorkbenchWindow().getShell(),
"Project creation error", "Project with this name already exists");
return false;
}
if (!project.isOpen()) {
project.open(null);
}
String transformationFolderName = "Transformations";
// Check subfolder name
if (!one.getRootFolderText().isEmpty()) {
transformationFolderName = one.getRootFolderText();
}
IFolder binFolder = project.getFolder(transformationFolderName);
if (!binFolder.exists()) {
one.createNewFolder(binFolder, false, true, null);
// Checks if user wants to create a CD example file
if (one.createCDExampleFile()) {
InputStream demoFileContents = null;
try {
// If the user wants to, an example file is created
URL url = new URL("platform:/plugin/cdtrans-editor/src/main/resources/exampleFiles/RefactorCDs");
InputStream inputStream = url.openConnection().getInputStream();
binFolder.getFile("RefactorCDs.cdtr").create(inputStream, true, null);
}
catch (IOException e) {
Log.error("TransProjectWizard: Error while creating Demo file", e);
MessageDialog.openError(this.workbench.getActiveWorkbenchWindow().getShell(),
"Example file creation error", "There was an error while creating the example file");
}
finally {
if (demoFileContents != null) {
try {
demoFileContents.close();
}
catch (IOException e) {
Log.error("TransProjectWizard: Error while closing file stream", e);
}
}
}
}
BasicNewResourceWizard.selectAndReveal(binFolder, this.workbench.getActiveWorkbenchWindow());
}
}
catch (CoreException e) {
Log.error("TransProjectWizard: Error while creating new Project", e);
}
}
return true;
}
}
But if I start this there is a runtime error if I try to open the wizard which says:
I already tried to export the plug-in and install it in a fresh Eclipse installation, where the m2e package is installed, but with the same result.
Any thoughts on how to fix it?
Hi I've been trying all night to run this example and have had no luck what so ever, I cannot find a solution. I have two file.
First is Worker.java and here is its contents
import javafx.application.Application;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* 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.
*/
/**
*
* #author brett
*/
public class Worker {
/**
* #param args the command line arguments
* #throws java.lang.Exception
*/
/**
*
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
doit();
}
private static void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
mytask.call();
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Next is the IteratingTask.java file and its contents
//import javafx.concurrent.Task;
import javafx.application.Application;
import javafx.concurrent.Task;
/**
*
* #author brett
*/
public class IteratingTask extends Task<Integer> {
private final int totalIterations;
public IteratingTask(int totalIterations) {
this.totalIterations = totalIterations;
}
#Override protected Integer call() throws Exception {
int iterations;
// iterations = 0;
for (iterations = 0; iterations < totalIterations; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, totalIterations);
}
return iterations;
}
}
I know I'm doing something very wrong but... I just cant see it.
Here is the error it get
run:
Jan 31, 2015 11:56:38 PM Worker doit
SEVERE: null
java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:270)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:265)
at javafx.application.Platform.runLater(Platform.java:81)
at javafx.concurrent.Task.runLater(Task.java:1211)
at javafx.concurrent.Task.updateMessage(Task.java:1129)
at IteratingTask.call(IteratingTask.java:24)
at Worker.doit(Worker.java:38)
at Worker.main(Worker.java:31)
BUILD SUCCESSFUL (total time: 0 seconds)
It builds ok.... any advice would be awesome.
The problem is that the FX Toolkit, and in particular the FX Application Thread have not been started. The update...(...) methods in Task update various state on the FX Application Thread, so your calls to those methods cause an IllegalStateException as there is no such thread running.
If you embed this code in an actual FX Application, it will run fine. Calling launch() causes the FX toolkit to be started.
Also, note that while this will run, Tasks are generally intended to be run in a background thread, as below:
import javafx.application.Application;
import javafx.scene.Scene ;
import javafx.scene.layout.StackPane ;
import javafx.scene.control.Label ;
import javafx.stage.Stage ;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Worker extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane(new Label("Hello World"));
Scene scene = new Scene(root, 350, 75);
primaryStage.setScene(scene);
primaryStage.show();
doit();
}
public static void main(String[] args) throws Exception {
launch(args);
}
private void doit(){
try {
IteratingTask mytask = new IteratingTask(800000);
// mytask.call();
Thread backgroundThread = new Thread(mytask);
backgroundThread.start(); // will return immediately, task runs in background
System.out.println(mytask.getValue());
int pro = (int) mytask.getProgress();
System.out.println(pro);
} catch (Exception ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I am in a Linux Envirnomnet. I am also using Netbeans. Here is my code below:
import java.io.*;
public class myFirstJavaProgram {
public static void main(String[] args) {
File file = new File("home/gk/Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
}
}
You forgot a slash before home. It is looking for a folder that most likely does not exist inside the classpath.
EDIT
After you pointed out the exception you were receiving I realized that a checked exception is not being handled. You need to catch the possible IOException or include the exception in the method signature.
import java.io.*;
/**
*
* #author Ashwin Parmar
*/
public class myFirstJavaProgram {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
File file = new File("/home/gk/Hello1.txt");
file.createNewFile();
} catch(IOException e) {
System.out.println(e.getMessage());
}
// creates a FileWriter Object
}
}
When dealing with any File IO action in Java, it is always best to use a try/catch loop
Error in your path.
This home/gk/Hello1.txt should be /home/gk/Hello1.txt
Just playing around with java trying to learn it etc.
Here is my code so far, using HtmlUnit.
package hsspider;
import com.gargoylesoftware.htmlunit.WebClient;
/**
* #author
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("starting ");
Spider spider = new Spider();
spider.Test();
}
}
package hsspider;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
/**
* #author
*/
public class Spider {
public void Test() throws Exception
{
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://www.google.com");
System.out.println(page.getTitleText());
}
}
I am using Netbeans.
I can't seem to figure out what the problem is, why doesn't it compile?
The error:
C:\Users\mrblah\.netbeans\6.8\var\cache\executor-snippets\run.xml:45:
Cancelled by user.
BUILD FAILED (total time: 0 seconds)
The row in the xml is:
<translate-classpath classpath="${classpath}" targetProperty="classpath-translated" />
Test is declared to throw Exception. If you add "throws Exception" to your main method it should compile. For example:
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
System.out.println("starting ");
Spider spider = new Spider();
spider.Test();
}
What Steve said is correct. But maybe there are some problems with the uppercase character of Test. A method always starts with a lower case character. So test would be better.
Unchecking the "Compile on Save" option of the "Properties" tab in Netbeans 7.1.2 resolved a similar error message for me.