import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.VideoCapture;
import org.opencv.objdetect.CascadeClassifier;
public class WebCam extends JPanel implements ActionListener{
private BufferedImage image;
public JButton button = new JButton("capture");
int count = 1;
public WebCam() {
super();
button.addActionListener((ActionListener) this);
this.add(button);
}
public BufferedImage getImage() {
return image;
}
public void setimage(BufferedImage newimage) {
image = newimage;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.image == null) {
return;
}
g.drawImage(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), null);
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("face capture");
frame.setSize(300,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
CascadeClassifier faceDetector = new CascadeClassifier("C:\\opencv\\sources\\data\\lbpcascades\\lbpcascade_frontalface.xml");
WebCam anan = new WebCam();
frame.add(anan);
frame.setVisible(true);
Mat webcam_image = new Mat();
MatToBufImg mat2Buf = new MatToBufImg();
VideoCapture capture = null;
try {
capture = new VideoCapture(0);
}
catch (Exception e){
}
if (capture.open(0)) {
while (true) {
capture.read(webcam_image);
if (!webcam_image.empty()) {
frame.setSize(webcam_image.width(), webcam_image.height());
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(webcam_image, faceDetections);
for (Rect rect : faceDetections.toArray()) {
Core.rectangle(webcam_image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));// mat2Buf, mat2Buf);
}
System.out.println("...............face detected: " + faceDetections.toArray().length);
if (faceDetections.toArray().length == 0) {
System.out.println("Face not detected!");
}
mat2Buf.setMatrix(webcam_image, ".jpg");
anan.setimage(mat2Buf.getBufferedImage());
anan.repaint();
}
else {
System.out.println("problem");
}
}
}
capture.release();
}
#Override
public void actionPerformed(ActionEvent e){
System.out.println("hellohellohellohellohello");
int width = 943;
int height = 640;
BufferedImage image = null;
File f = null;
String ans = JOptionPane.showInputDialog(null, "Color/Grey");
System.out.println(ans);
BufferedImage bi = image;
ImageIcon ii = null;
Image newimg = bi.getScaledInstance(320, 220, java.awt.Image.SCALE_SMOOTH);
ii = new ImageIcon(newimg);
Image i2 = ii.getImage();
image = new BufferedImage(i2.getWidth(null), i2.getHeight(null), BufferedImage.SCALE_SMOOTH);
image.getGraphics().drawImage(i2, 0, 0, null);
RenderedImage resim = null;
if (i2 instanceof RenderedImage) {
resim = (RenderedImage) i2;
} else {
BufferedImage anlikResim = null;
if (!ans.equalsIgnoreCase("color")) {
anlikResim = new BufferedImage(
ii.getIconWidth(),
ii.getIconHeight(),
BufferedImage.TYPE_BYTE_GRAY);
} else {
anlikResim = new BufferedImage(
ii.getIconWidth(),
ii.getIconHeight(),
BufferedImage.SCALE_SMOOTH);
}
Graphics2D g = anlikResim.createGraphics();
g.drawImage(i2, 0, 0, null);
g.dispose();
resim = anlikResim;
}
try {
f = new File("C:\\opencv\\build\\java\\x64\\");
ImageIO.write(resim, "jpg", f);
System.out.println("yes");
} catch (Exception ex) {
}
}
}
I am working on a face detection project. It used to work perfectly fine but suddenly ceased to work properly. When I run the program it gives a NullPointerException at line 120. How can I fix this problem?
Related
I'm trying to make a react-native project where i can enter the camera on the native side by clicking on a button on the react side.
it needs to click a single pic and send the path of file back to react Everything works fine. the file is being saved (1600X1200 resolution) but its not returning to react side and an error is coming i.e.:-
2019-05-30 15:32:49.497 28080-28132/com.gjcamera E/BufferItemConsumer: [ImageReader-1600x1200f100m1-28080-0] Failed to release buffer: Unknown error -1 (1).
I don't know where i am making a mistake.
here's my code:-
App.js:-
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, TouchableOpacity, NativeModules } from 'react-native';
const GJC = NativeModules.GJCamera;
type Props = {};
export default class App extends Component<Props> {
constructor() {
super();
this.state = {
imagePathh: "empty",
}
this.OpenMyCamera = this.OpenMyCamera.bind();
}
OpenMyCamera = async () => {
const result = await GJC.openCamera();
this.setState({ imagePathh: result });
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To enter camera, click on the "Camera" below</Text>
<Text style={styles.instructions}>The path of image will be shown below...</Text>
<TouchableOpacity style={{ backgroundColor: 'green' }} onPress={() => this.OpenMyCamera()}>
<Text style={{ color: '#fff' }}>Camera</Text>
</TouchableOpacity>
<Text style={{ paddingTop: 300 }}>The Path of image is </Text>
<Text style={{ color: "skyblue" }}>{this.state.imagePathh}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
GJCameraModule.java:-
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.HashMap;
import java.util.Map;
import static android.support.v4.content.ContextCompat.startActivity;
public class GJCameraModule extends ReactContextBaseJavaModule {
private Promise promise;
public GJCameraModule(ReactApplicationContext reactContext) {
super(reactContext);
}
#ReactMethod
public String show() {
String imagePath = "";
String imageName = "";
imageName = "";//GJCamera.sendPath();
imagePath = Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + imageName + ".jpg";
return imagePath.toString();
}
#ReactMethod
public void openCamera(final Promise promise) {
Toast.makeText(getReactApplicationContext(), "LOLZ", Toast.LENGTH_SHORT).show();
try {
GJCamera gjc = GJCamera.newInstance();
gjc.setPromise(promise);
Intent intent = new Intent(getCurrentActivity(), GJCamera.class);
getCurrentActivity().startActivity(intent);
Toast.makeText(getReactApplicationContext(), "LOLZ--Return", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
promise.reject(e.getMessage(), e.getMessage());
}
}
#Override
public String getName() {
return "GJCamera";
}
#Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
String android_id = Settings.System.getString(getReactApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
constants.put("uniqueId", android_id);
return constants;
}
}
GJCamera.java:-
package com.gjcamera;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.WritableMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;
public class GJCamera extends AppCompatActivity {
private ImageButton btnCapture;
private TextureView textureView;
public static String imgName;
private static Promise promise;
//Check state orientation of output image
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private String cameraId;
private CameraDevice cameraDevice;
private CameraCaptureSession cameraCaptureSessions;
private CaptureRequest.Builder captureRequestBuilder;
private Size imageDimension;
private ImageReader imageReader;
//Save to FILE
private File file;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private HandlerThread mBackgroundThread;
SurfaceTexture texture;
public static GJCamera newInstance() {
GJCamera a = new GJCamera();
return a;
}
CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice camera) {
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(#NonNull CameraDevice camera) {
// if (promise!=null) { promise.reject("Error");}
// promise = null;
cameraDevice = camera;
returnHome();
}
#Override
public void onError(#NonNull CameraDevice camera, int i) {
// if (promise!=null) { promise.reject("Error");}
// promise = null;
cameraDevice = camera;
returnHome();
}
};
public void setPromise(Promise promise) {
this.promise = promise;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gjcamera);
textureView = findViewById(R.id.textureView);
//From Java 1.4 , you can use keyword 'assert' to check expression true or false
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
btnCapture = findViewById(R.id.clickButton);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
takePicture();
}
});
}
private void takePicture() {
if (cameraDevice == null)
return;
CameraManager manager = null;
manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null)
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
.getOutputSizes(ImageFormat.JPEG);
//Capture image with custom size
int width = 1600;
int height = 1200;
imageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(imageReader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(imageReader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
//Check orientation base on device
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
file = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/IMG_" + calendar.get(Calendar.YEAR) + calendar.get(Calendar.MONTH) + calendar.get(Calendar.DATE) + "_" + calendar.get(Calendar.HOUR_OF_DAY) + calendar.get(Calendar.MINUTE) + calendar.get(Calendar.SECOND) + ".jpg");
ImageReader.OnImageAvailableListener readerListener = null;
readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReadr) {
Image image = null;
try {
image = imageReader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
{
if (image != null)
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
} finally {
if (outputStream != null)
outputStream.close();
}
}
};
imageReader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(GJCamera.this, "Saved " + file, Toast.LENGTH_SHORT).show();
returnHome();
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
try {
cameraCaptureSession.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
// cameraDevice.close();
//convertFileToWritableMap(file));
// promise = null;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void returnHome() {
texture.release();
// if(imageReader != null) {
// imageReader.close();
// imageReader = null;
// }
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
}
if (cameraCaptureSessions != null) {
cameraCaptureSessions.close();
cameraCaptureSessions = null;
}
if (promise != null) {
promise.resolve(convertFileToWritableMap(file));
promise = null;
}
}
private void createCameraPreview() {
try {
texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(1600, 1200);
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if (cameraDevice == null)
return;
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(GJCamera.this, "Changed", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
//Check realtime permission if run higher API 23
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You can't use camera without permission", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if (textureView.isAvailable())
openCamera();
else
textureView.setSurfaceTextureListener(textureListener);
}
#Override
protected void onPause() {
stopBackgroundThread();
super.onPause();
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
public static WritableMap convertFileToWritableMap(File fileLocation) {
WritableMap newFile = Arguments.createMap();
if (fileLocation == null) return newFile;
newFile.putString("imgPath", fileLocation.getPath());
return newFile;
}
}
activity_gjcamera.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gjcamera.MainActivity">
<TextureView
android:id="#+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/clickButton"
/>
<ImageButton
android:id="#+id/clickButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/camera_click" />
</RelativeLayout>
BTW, Thanks for the help.
finally, found it:-
in GJCamera.java within returnHome() Method:-
if (promise != null) {
promise.resolve(convertFileToWritableMap(file));
promise = null;
}
change it to:-
if (promise != null) {
promise.resolve(convertFileToWritableMap(file));
promise = null;
finish(); // in order to finish the activity.
}
The entire project is present Here.
I have coded a simple card game (using IntelliJ 3.3) that updates gui each second and contains many nodes in game which are used to display game events and animation. People who have tried the game said that their system slows down and memory and cpu usage goes up (I was shocked when I saw from one of my friend's screen that it used around 1.4 GB ram) is this supposed to happen?
I have checked some questions related to javaFX memory usage problems but could not relate to my matter. In one article, I read that using many nodes in a JavaFX game might result in high memory usage.
in a short runtime:
minimum memory usage is around 100-250 MB
maximum memory usage is around 800-1200 MB
average memory usage is around 500-700 MB
IMPORTANT:
THERE ARE 100 BUTTONS IN A 10X10 GRIDPANE WHICH DO NOT HAVE FX IDS
in gameButtonClicked matches are found buttons.indexOf(event.getSource())
UML DIAGRAM
Main.java
IMPORTS:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class Main extends Application {
static boolean isMuted;
static Stage window;
static MediaPlayer mediaPlayerBGM;
static MediaPlayer mediaPlayerSFX;
private static HashMap<String, Media> sounds;
private static ArrayList<Long> usage;
private final String[] SOUND_LIST = {"bgm_credits.mp3", "bgm_game.mp3", "bgm_game_1.mp3", "bgm_game_2.mp3", "bgm_game_3.mp3",
"bgm_how_to.mp3", "bgm_menu.mp3", "bgm_victory.mp3", "sfx_button_clicked.wav",
"sfx_card_unfold.wav", "sfx_toggle.wav"
};
public static void main(String[] args) {
launch(args);
AtomicLong sum = new AtomicLong();
usage.forEach(sum::addAndGet);
long average = sum.get() / usage.size();
System.out.printf("minimum usage: %d, maximum usage: %d, average usage: %d",
Collections.min(usage), Collections.max(usage), average);
}
static void playBGM(String key) {
mediaPlayerBGM.stop();
mediaPlayerBGM.setStartTime(Duration.ZERO);
if (key.equals("bgm_game")) {
String[] suffix = {"", "_1", "_2", "_3"};
Random random = new Random();
mediaPlayerBGM = new MediaPlayer(sounds.get(key + suffix[random.nextInt(4)]));
} else {
mediaPlayerBGM = new MediaPlayer(sounds.get(key));
}
mediaPlayerBGM.setCycleCount(MediaPlayer.INDEFINITE);
if (isMuted) {
mediaPlayerBGM.setVolume(0.0);
}
mediaPlayerBGM.play();
}
static void playSFX(String key) {
if (mediaPlayerSFX != null) {
mediaPlayerSFX.stop();
}
mediaPlayerSFX = new MediaPlayer(sounds.get(key));
if (isMuted) {
mediaPlayerSFX.setVolume(0.0);
}
mediaPlayerSFX.play();
}
#Override
public void start(Stage primaryStage) throws Exception {
sounds = new HashMap<>();
usage = new ArrayList<>();
isMuted = false;
for (String soundName :
SOUND_LIST) {
URL resource = getClass().getResource("/" + soundName);
System.out.println(soundName);
System.out.println(resource.toString());
sounds.put(soundName.substring(0, soundName.lastIndexOf('.')), new Media(resource.toString()));
}
mediaPlayerBGM = new MediaPlayer(sounds.get("bgm_menu"));
mediaPlayerBGM.setCycleCount(MediaPlayer.INDEFINITE);
mediaPlayerBGM.play();
window = primaryStage;
Parent root = FXMLLoader.load(getClass().getResource("menu.fxml"));
// long running operation runs on different thread
Thread thread = new Thread(() -> {
Runnable updater = () -> {
if (!Game.isGameIsOver() && Game.getScore() != 0 && window.getTitle().equals("The Main Pick") &&
Game.firstClickHappened()) {
Game.scoreCalculator();
}
};
while (true) {
try {
usage.add(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
System.out.printf("Used memory: %d\n", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Interrupted");
}
// UI update is run on the Application thread
Platform.runLater(updater);
}
});
// don't let thread prevent JVM shutdown
thread.setDaemon(true);
thread.start();
window.setTitle("Main Menu");
window.setScene(new Scene(root, 600, 600));
window.setResizable(false);
window.show();
}
}
Controller.java
IMPORTS:
package com.sample;
import javafx.animation.FadeTransition;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
importjavafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.util.Duration;
import java.io.IOException;
public class Controller
{
#FXML
public RadioButton musicOnOff;
#FXML
public Button newGame;
#FXML
public Button howTo;
#FXML
public Button credits;
#FXML
public Button exit;
#FXML
public Button menu;
#FXML
public GridPane pane;
#FXML
public Label score;
#FXML
public Label time;
#FXML
public Label tries;
private boolean animating;
public void initialize() {
if (score != null && time != null && tries != null) {
score.textProperty().bind(Game.scoreProperty);
time.textProperty().bind(Game.timeProperty);
tries.textProperty().bind(Game.triesProperty);
animating=false;
}
if (musicOnOff!=null){
if(Main.isMuted){
musicOnOff.setSelected(true);
}
}
}
public void newGameButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
new Game();
Main.window.hide();
Main.window.setScene(getScene("game"));
Main.window.setTitle("The Main Pick");
Main.window.setMaximized(true);
Main.playBGM("bgm_game");
Main.window.show();
} catch (IOException e) {
System.out.println("could not change the scene to: game");
}
}
public void menuButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
Main.playBGM("bgm_menu");
if (Main.window.getTitle().equals("The Main Pick")) {
Main.window.hide();
Game.setGameOver();
Main.window.setScene(getScene("menu"));
Main.window.setMaximized(false);
Main.window.show();
} else {
Main.window.setScene(getScene("menu"));
}
Main.window.setTitle("Main Menu");
} catch (IOException e) {
System.out.println("could not change the scene to: game");
}
}
public void gameButtonClicked(ActionEvent event) {
ObservableList<Node> buttons = pane.getChildren();
int index = buttons.indexOf(event.getSource());
int column = index % 10;
int row = (index - index % 10) / 10;
if (!((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure") &&
!((Button) event.getSource()).getStyleClass().toString().equals("button button-uncovered"))
{
FadeTransition transition = new FadeTransition();
transition.setNode((Button) event.getSource());
transition.setDuration(new Duration(500));
transition.setFromValue(1.0);
transition.setToValue(0.0);
transition.setCycleCount(1);
transition.setOnFinished(actionEvent -> {
if (((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure")) {
loadVictoryScene();
}
if (!((Button) event.getSource()).getStyleClass().toString().equals("button button-treasure") &&
!((Button) event.getSource()).getStyleClass().toString().equals("button button-uncovered"))
{
transition.setFromValue(0.0);
transition.setToValue(1.0);
System.out.println(((Button) event.getSource()).getStyleClass().toString());
((Button) event.getSource()).getStyleClass().remove("button-covered");
((Button) event.getSource()).getStyleClass().add(Game.click(row, column));
transition.play();
transition.setOnFinished(ActionEvent->animating=false);
}
});
System.out.println(animating);
if(!animating){
animating=true;
transition.play();
Main.playSFX("sfx_card_unfold");}
}
System.out.printf("button index:%d,row:%d,column:%d\n", index, row, column);
}
public void howToPlayButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
Main.playBGM("bgm_how_to");
Main.window.setScene(getScene("howTo"));
Main.window.setTitle("How to Play");
} catch (IOException e) {
System.out.println("could not change the scene to: how to play");
}
}
public void creditsButtonClicked() {
try {
Main.playSFX("sfx_button_clicked");
Main.playBGM("bgm_credits");
Main.window.setScene(getScene("credits"));
Main.window.setTitle("Credits");
} catch (IOException e) {
System.out.println("could not change the scene to: credits");
}
}
public void exitButtonClicked() {
Main.playSFX("sfx_button_clicked");
Main.window.close();
}
public void musicOnOffRadioButtonChecked() {
Main.playSFX("sfx_toggle");
if (musicOnOff.isSelected()) {
Main.isMuted=true;
Main.mediaPlayerBGM.setVolume(0.0);
Main.mediaPlayerSFX.setVolume(0.0);
System.out.println("now selected");
} else {
Main.isMuted=false;
Main.mediaPlayerBGM.setVolume(1.0);
Main.mediaPlayerSFX.setVolume(1.0);
System.out.println("unselected");
}
}
private void loadVictoryScene() {
try {
Main.window.hide();
Main.playBGM("bgm_victory");
Main.window.setScene(getScene("victory"));
Main.window.setTitle("Victory");
Main.window.setMaximized(false);
Main.window.show();
} catch (IOException e) {
System.out.println("could not change the scene to: victory");
}
}
private Scene getScene(String name) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource(name + ".fxml"));
if (name.equals("game")) {
return new Scene(root, 800, 800);
}
return new Scene(root, 600, 600);
}
}
Game.java
IMPORTS:
package com.sample;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.util.Random;
public class Game {
static StringProperty scoreProperty;
static StringProperty timeProperty;
static StringProperty triesProperty;
private static int time;
private static int score;
private static int tries;
private static int[][] tiles;
private static boolean gameIsOver;
private static boolean firstClick;
public Game() {
System.out.println("Game created...");
tries = 0;
score = 100000;
time = 0;
gameIsOver = false;
firstClick = false;
scoreProperty = new SimpleStringProperty("" + score);
timeProperty = new SimpleStringProperty("0");
triesProperty = new SimpleStringProperty("0");
tiles = new int[10][10];
Random random = new Random();
int treasureColumn = random.nextInt(10);
int treasureRow = random.nextInt(10);
tiles[treasureRow][treasureColumn] = 1;
}
static boolean firstClickHappened() {
return firstClick;
}
static void setGameOver() {
gameIsOver = true;
}
static boolean isGameIsOver() {
return gameIsOver;
}
static int getScore() {
return score;
}
static void scoreCalculator() {
time++;
if (time < 10) {
score = score - 100;
} else if (time < 20) {
score = score - 200;
} else if (time < 30) {
score = score - 300;
} else if (time < 50) {
score = score - 500;
} else {
score = score - 1000;
}
if (score < 0) {
score = 0;
}
scoreProperty.setValue("" + score);
timeProperty.setValue("" + time);
triesProperty.setValue("" + tries);
System.out.printf("Score:%s,Time:%s,Tries%s\n", scoreProperty.getValue(), timeProperty.getValue(), triesProperty.getValue());
}
static String click(int row, int column) {
if (!firstClickHappened()) firstClick = true;
System.out.println(row + "," + column);
int clickValue = tiles[row][column];
System.out.println(clickValue);
if (clickValue == 0) {
tries++;
score -= 1000;
} else {
setGameOver();
}
return (clickValue == 1) ? "button-treasure" : "button-uncovered";
}
}
Below is the code that I wrote:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
for(int a=0,i=0;list.get(i)!=42;i++){
a=sc.nextInt();
list.add(i,a);
}
for(int i=0;i<list.size();i++){
out.println(list.get(i));
}
}
}
And this is the error im getting:
Execution failed.
java.lang.IndexOutOfBoundsException : Index: 0, Size: 0
Stack Trace:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Uni.main(Uni.java:8)
Can you please help with what to do?
Maybe you wanted to use a while cycle? It's much easier to initialize the list.
Furthermore, your code is checking if list.get(i) is not equal to 42, but you cannot do that because your list at the index 0 is still null.
A solution could be:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0;
while(i!=42) {
list.add(i++,sc.nextInt());
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
EDIT: to stop after the Input is 42:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0
while (true) {
int in = sc.nextInt();
if (in==42) break;
list.add(i++,sc.nextInt())
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
Is it possible to try out the new PHREAKS algorithm but using the conventional API from Drools 5.5
* EDIT: to make the question more precise *
conventional 5.5 API
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
instead new Drools 6 API
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.conf.ClockTypeOption;
It's also possible with the 5 knowledge api in drools 6.0+ by setting a rule engine property:
drools.ruleEngine = phreak
Here's how you set in the 5 knowledge api:
knowledgeBaseConfiguration.setProperty("drools.ruleEngine", "phreak");
I'm copy-pasting the simplest Java code for launching a 6.0 session. Everything else - fact insertion, global definitions,... works using the same API, only with KieSession.
package simple;
import java.io.FileInputStream;
import org.kie.api.KieServices;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Results;
import org.kie.api.builder.Message;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieContainer;
public class Main {
private KieSession kieSession;
public void build() throws Exception {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
FileInputStream fis = new FileInputStream( "simple/simple.drl" );
kfs.write( "src/main/resources/simple.drl",
kieServices.getResources().newInputStreamResource( fis ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
kieSession = kieContainer.newKieSession();
}
public void exec(){
kieSession.fireAllRules();
}
public static void main( String[] args ) throws Exception {
Main m = new Main();
m.build();
m.exec();
}
}
Yes, most of the API is still supported. You will need to add the knowledge-api jar to your classpath (https://github.com/droolsjbpm/drools/tree/master/knowledge-api-legacy5-adapter).
The main difference is that Drools 6 no longer uses PKG for deployment. It uses mavenized kjars now. If you are not using PKG files (built by guvnor in Drools 5), you should be fine.
the working code to preserve rules and facts by using the same KieSession and deploy Jars, the code is adapted from here https://github.com/droolsjbpm/drools/blob/master/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java.
package test.drools;
import java.io.UnsupportedEncodingException;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class Playground4 {
private String newline = System.getProperty("line.separator");
public static void main(String[] args) {
Playground4 pg = new Playground4();
try {
pg.doRules();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private String generateDRLString(int start, int end) {
StringBuilder sb;
sb = new StringBuilder();
sb.append("package performance.drools;" + newline);
for (int i = start; i <= end; i++) {
sb.append("rule \"R" + i + "\"" + newline);
sb.append("when" + newline);
sb.append("then" + newline);
sb.append("System.out.println(\"rule" + i + " fired!\");" + newline);
sb.append("end" + newline);
}
return sb.toString();
}
int count = 1;
public void doRules() throws UnsupportedEncodingException {
KieServices kieServices = KieServices.Factory.get();
KieBaseConfiguration kieBaseConf = kieServices.newKieBaseConfiguration();
//kieBaseConf.setProperty("drools.ruleEngine", "phreak");
kieBaseConf.setProperty("drools.ruleEngine", "phreak");
ReleaseId releaseId;
KieModule kieModule;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
// create session without rules for version 1.1.0
kieModule = createAndDeployJar(releaseId);
KieContainer kieContainer = kieServices.newKieContainer(kieModule
.getReleaseId());
kieContainer.newKieBase(kieBaseConf);
KieSession kieSession = kieContainer.newKieSession();
// Create an in-memory jar for version 1.2.0
count++;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
kieModule = createAndDeployJar(releaseId, generateDRLString(1, 3));
kieContainer.updateToVersion(releaseId);
kieSession.insert(new Object());
// Create an in-memory jar for version 1.3.0
count++;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
kieModule = createAndDeployJar(releaseId, generateDRLString(4, 12));
kieContainer.updateToVersion(releaseId);
kieSession.fireAllRules();
System.out.println(kieSession.getFactCount());
}
public KieModule createAndDeployJar(ReleaseId releaseId, String... drls) {
KieServices kieServices = KieServices.Factory.get();
byte[] jar = createKJar(kieServices, releaseId, null, drls);
return deployJar(kieServices, jar);
}
KieFileSystem kfs;
public byte[] createKJar(KieServices ks, ReleaseId releaseId,
String pom, String... drls) {
if (kfs == null) kfs = ks.newKieFileSystem();
if (pom != null) {
kfs.write("pom.xml", pom);
} else {
kfs.generateAndWritePomXML(releaseId);
}
for (int i = 0; i < drls.length; i++) {
if (drls[i] != null) {
kfs.write("src/main/resources/r" + 10 * count + i + ".drl", drls[i]);
}
}
KieBuilder kb = ks.newKieBuilder(kfs).buildAll();
if (kb.getResults()
.hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
for (org.kie.api.builder.Message result : kb.getResults()
.getMessages()) {
System.out.println(result.getText());
}
return null;
}
InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
.getKieModule(releaseId);
byte[] jar = kieModule.getBytes();
return jar;
}
public KieModule deployJar(KieServices ks, byte[] jar) {
// Deploy jar into the repository
Resource jarRes = ks.getResources().newByteArrayResource(jar);
KieModule km = ks.getRepository().addKieModule(jarRes);
return km;
}
}
This runs perfectly:
package sledmonitor;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class GetList3 {
private Connection conn;
private String ConnectURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=." + File.separator + "db" + File.separator + "sledprod.mdb";
private String user = "";
private String pw = "";
String offer;
GetList3(String sql){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection(ConnectURL, user, pw);
Statement stmt = conn.createStatement();
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
offer = rs.getString("offernumber");
System.out.println(offer);
}
rs.close();
stmt.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(conn!=null){
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
Now I would like to show the Results in a JTable. So I make this, what normaly should work:
while(rs.next()){
offer = rs.getString("offernumber");
List.tablemodel.addRow(new String[]{offer});
}
But this somehow throws following NullPointerException:
SELECT o.offernumber, o.TotalMPL
FROM sled_offers o left join sled_changes c on o.offerguid = c.objectid
WHERE (c.nextsequencenr is null or c.nextsequencenr=99999) AND TotalMPL='0'
AND (o.offerstate=2 or o.offerstate=4 or o.offerstate=5)
java.lang.NullPointerException
at sledmonitor.GetList3.<init>(GetList3.java:28)
at sledmonitor.GetList.<init>(GetList.java:45)
at sledmonitor.Monitor$4.mouseClicked(Monitor.java:99)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6508)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:703)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:676)
at java.awt.EventQueue$4.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:673)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
The class List looks like this:
package sledmonitor;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class List extends JFrame {
private JPanel contentPane;
private JTable table;
static DefaultTableModel tablemodel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
List frame = new List();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public List() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
tablemodel = new DefaultTableModel();
tablemodel.addColumn("OfferNumber");
table = new JTable(tablemodel);
scrollPane.setViewportView(table);
}
}
Any idea?
You seem to be accessing the static field List.tablemodel without instanciating first the List object, so you aren't calling List() which doesn't instanciate your tablemodel object.
You should then use a static constructor:
static {
tablemodel = new DefaultTableModel();
tablemodel.addColumn("OfferNumber");
}
And remove those 2 lines of code from the List() constructor.
use this
DefaultTableModel myData = new DefaultTableModel();
JTable table = new JTable(myData);
// initialize the table with model type constructor
while(rs.next()){
String offer = rs.getString("offernumber");
Object [] rowData=new Object[]{offer,null};
myData.addRow(rowData);
}
//use addRow(Object[] rowData) method of defaulttablemodel class