I've created an RCP application with an interactive splash for logging onto my system. I built it on a Mac, and the application works perfectly, but when I created a new product configuration for Windows and run the application, it launches without the splash and there are no errors appearing in the console.
The splash handler code is as follows
/**
* The splash screen controller for the RCP application. This has been modified to also act as a login screen for the
* application. Failure to correctly authenticate results in the application termination.
*/
package com.myproject.plugins.core.splashHandlers;
import java.net.MalformedURLException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.splash.AbstractSplashHandler;
/**
* The splash handler overrides the default RCP splash handler.
* #since 3.3
*/
public class InteractiveSplashHandler extends AbstractSplashHandler {
/**
* Composite container for login form.
*/
private Composite loginComposite;
/**
* Text box input for login username.
*/
private Text usernameTextBox;
/**
* Text box input for login password.
*/
private Text passwordTextBox;
/**
* OK button for submission of the login form.
*/
private Button okButton;
/**
* Cancel button for cancelling the login attempt and exiting the application.
*/
private Button cancelButton;
/**
* Simple boolean flag to store login success/status.
*/
private boolean isAuthenticated;
/**
* SWT form label for username.
*/
private Label usernameLabel;
/**
* SWT form label for password.
*/
private Label passwordLabel;
/**
* Form/layout data for username label.
*/
private FormData usernameLabelFormData;
/**
* Form/layout data for password label.
*/
private FormData passwordLabelFormData;
/**
* Form/layout data for username text box.
*/
private FormData usernameTextBoxFormData;
/**
* Form/layout data for password text box.
*/
private FormData passwordTextBoxFormData;
/**
* Form/layout data for OK button.
*/
private FormData okButtonFormData;
/**
* Constructor for the splash handler.
*/
public InteractiveSplashHandler() {
passwordTextBox = null;
cancelButton = null;
isAuthenticated = false;
}
/**
* Initialiser for the splash screen.
* #see org.eclipse.ui.splash.AbstractSplashHandler#init(org.eclipse.swt.widgets.Shell)
*/
public void init(final Shell splash) {
/**
* Initialising the parent SplashHandler with the splash shell.
*/
super.init(splash);
/**
* Configure the shell UI layout.
*/
configureUISplash();
/**
* Create UI components.
*/
createUI();
/**
* Create UI listeners.
*/
createUIListeners();
/**
* Force the splash screen to layout.
*/
splash.layout(true);
/**
* Keep the splash screen visible and prevent the RCP application from loading until the close button is
* clicked.
*/
doEventLoop();
}
/**
* Create the event loop for the splash to prevent the application load from completion, and hold it at the splash
* until the login event is successful.
*/
private void doEventLoop() {
Shell splash = getSplash();
while (isAuthenticated == false) {
if (splash.getDisplay().readAndDispatch() == false) {
splash.getDisplay().sleep();
}
}
}
/**
* Create the UI listeners for all the form components.
*/
private void createUIListeners() {
/**
* Create the OK button listeners.
*/
createUIListenersButtonOK();
/**
* Create the cancel button listeners.
*/
createUIListenersButtonCancel();
}
/**
* Listeners setup for the cancel button.
*/
private void createUIListenersButtonCancel() {
cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonCancelWidgetSelected();
}
});
}
/**
* Handles the cancel action by shutting down the RCP application.
*/
private void handleButtonCancelWidgetSelected() {
/**
* Abort the loading of the RCP application.
*/
getSplash().getDisplay().close();
System.exit(0);
}
/**
* Listeners setup for the OK button.
*/
private void createUIListenersButtonOK() {
okButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleButtonOKWidgetSelected();
}
});
}
/**
* Handles the OK button being pressed and the login attempted.
*/
private void handleButtonOKWidgetSelected() {
String username = usernameTextBox.getText();
String password = passwordTextBox.getText();
AuthenticationClient client = new AuthenticationClient();
if (username.equals("") || password.equals("")) {
MessageDialog.openError(getSplash(),
"Authentication Failed", //$NON-NLS-1$
"A username and password must be specified to login."); //$NON-NLS-1$
} else {
try {
if (client.authenticate(username, password)) {
isAuthenticated = true;
} else {
MessageDialog.openError(getSplash(),
"Authentication Failed", //$NON-NLS-1$
"The details you entered could not be verified."); //$NON-NLS-1$
}
} catch (MalformedURLException e) {
MessageDialog.openError(getSplash(),
"Authentication Failed", //$NON-NLS-1$
"Service responded with an error."); //$NON-NLS-1$
}
}
}
/**
* Calls the individual UI component creation functions.
*/
private void createUI() {
/**
* Create the login panel.
*/
createUICompositeLogin();
/**
* Create the user name label.
*/
createUILabelUserName();
/**
* Create the user name text widget.
*/
createUITextUserName();
/**
* Create the password label.
*/
createUILabelPassword();
/**
* Create the password text widget.
*/
createUITextPassword();
/**
* Create the OK button.
*/
createUIButtonOK();
/**
* Create the cancel button.
*/
createUIButtonCancel();
}
/**
* Creates the SWT component for the cancel button.
*/
private void createUIButtonCancel() {
/**
* Create the button.
*/
cancelButton = new Button(loginComposite, SWT.PUSH);
okButtonFormData.right = new FormAttachment(cancelButton, -6);
FormData cancelButtonFormData = new FormData();
cancelButtonFormData.left = new FormAttachment(0, 392);
cancelButtonFormData.right = new FormAttachment(100, -10);
cancelButtonFormData.bottom = new FormAttachment(100, -10);
cancelButton.setLayoutData(cancelButtonFormData);
cancelButton.setText("Cancel");
}
/**
* Creates the SWT component for the OK button.
*/
private void createUIButtonOK() {
/**
* Create the button.
*/
okButton = new Button(loginComposite, SWT.PUSH);
passwordTextBoxFormData.bottom = new FormAttachment(okButton, -6);
okButtonFormData = new FormData();
okButtonFormData.left = new FormAttachment(0, 279);
okButtonFormData.bottom = new FormAttachment(100, -10);
okButton.setLayoutData(okButtonFormData);
okButton.setText("OK");
}
/**
* Creates the SWT component for the password text box.
*/
private void createUITextPassword() {
/**
* Create the text widget.
*/
int style = SWT.PASSWORD | SWT.BORDER;
passwordTextBox = new Text(loginComposite, style);
passwordLabelFormData.right = new FormAttachment(passwordTextBox, -6);
passwordTextBoxFormData = new FormData();
passwordTextBoxFormData.right = new FormAttachment(100, -10);
passwordTextBoxFormData.left = new FormAttachment(0, 279);
passwordTextBox.setLayoutData(passwordTextBoxFormData);
}
/**
* Creates the SWT component for the password label.
*/
private void createUILabelPassword() {
/**
* Create the label.
*/
passwordLabel = new Label(loginComposite, SWT.NONE);
passwordLabelFormData = new FormData();
passwordLabelFormData.top = new FormAttachment(usernameLabel, 11);
passwordLabel.setLayoutData(passwordLabelFormData);
passwordLabel.setText("&Password:");
}
/**
* Creates SWT component for the username text box.
*/
private void createUITextUserName() {
/**
* Create the text widget.
*/
usernameTextBox = new Text(loginComposite, SWT.BORDER);
usernameLabelFormData.top = new FormAttachment(usernameTextBox, 3, SWT.TOP);
usernameLabelFormData.right = new FormAttachment(usernameTextBox, -6);
usernameTextBoxFormData = new FormData();
usernameTextBoxFormData.top = new FormAttachment(0, 233);
usernameTextBoxFormData.right = new FormAttachment(100, -10);
usernameTextBoxFormData.left = new FormAttachment(0, 279);
usernameTextBox.setLayoutData(usernameTextBoxFormData);
}
/**
* Creates SWT component for the username label.
*/
private void createUILabelUserName() {
/**
* Create the label
*/
usernameLabel = new Label(loginComposite, SWT.NONE);
usernameLabelFormData = new FormData();
usernameLabel.setLayoutData(usernameLabelFormData);
usernameLabel.setText("&User Name:");
}
/**
* Creates SWT component for the login composite.
*/
private void createUICompositeLogin() {
/**
* Create the composite and set the layout.
*/
loginComposite = new Composite(getSplash(), SWT.BORDER);
loginComposite.setLayout(new FormLayout());
}
/**
* Configures the splash screen SWT/UI components.
*/
private void configureUISplash() {
/**
* Configure layout
*/
FillLayout layout = new FillLayout();
getSplash().setLayout(layout);
/**
* Force shell to inherit the splash background
*/
getSplash().setBackgroundMode(SWT.INHERIT_DEFAULT);
}
}
Oddly enough, the bitmap (created in Photoshop/Mac) image was seen as corrupt in Eclipse, but opened fine in all graphics applications (including Photoshop/Win). I opened the file in MS Paint and saved without changes. The splash started working fine.
Check your bitmap if you get this error!
Related
After Message save broadcasting occurs this issue:
local.ERROR: {"userId":3,"exception":"[object] (Pusher\ApiErrorException(code: 0): at C:\xampp\htdocs\fm\script\vendor\pusher\pusher-php-server\src\Pusher.php:533)
[stacktrace]
#0 C:\xampp\htdocs\fm\script\vendor
nahid\talk\src\Live\Webcast.php(51): Pusher\Pusher->trigger(Array, 'talk-send-messa...', Array)
nahid\talk\src\Live\Broadcast.php(85): Nahid\Talk\Live\Broadcast->dispatch(Object(Nahid\Talk\Live\Webcast))
#22 C:\xampp\htdocs\fm\script\vendor
nahid\talk\src\Talk.php(106): Nahid\Talk\Live\Broadcast->transmission(Object(Nahid\Talk\Messages\Message))
#23 C:\xampp\htdocs\fm\script\vendor
nahid\talk\src\Talk.php(268): Nahid\Talk\Talk->makeMessage(2, Object(Nahid\Talk\Messages\Message))
Pages:
Webcast.php
class Webcast implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
/*
* Message Model Instance
*
* #var object
* */
protected $message;
/*
* Broadcast class instance
*
* #var object
* */
protected $broadcast;
/**
* Set message collections to the properties.
*/
public function __construct($message)
{
$this->message = $message;
}
/*
* Execute the job and broadcast to the pusher channels
*
* #param \Nahid\Talk\Live\Broadcast $broadcast
* #return void
*/
public function handle(Broadcast $broadcast)
{
$this->broadcast = $broadcast;
$senderIdKey = $this->broadcast->getConfig('user.ownerKey') ? $this->broadcast->getConfig('user.ownerKey') : 'id';
$toUser = ($this->message['sender'][ $senderIdKey] == $this->message['conversation']['user_one']) ? $this->message['conversation']['user_two'] : $this->message['conversation']['user_one'];
$channelForUser = $this->broadcast->getConfig('broadcast.app_name').'-user-'.$toUser;
$channelForConversation = $this->broadcast->getConfig('broadcast.app_name').'-conversation-'.$this->message['conversation_id'];
// try {
$this->broadcast->pusher->trigger([sha1($channelForUser), sha1($channelForConversation)], 'talk-send-message', $this->message);
// } catch (ApiErrorException $e) {
// throw new BroadcastException(
// sprintf('Pusher error: %s.', $e->getMessage())
// );
// }
}
}
Broadcast.php
class Broadcast
{
use DispatchesJobs;
/*
* Constant for talk config prefix
*
* #const string
* */
const CONFIG_PATH = 'talk';
/*
* Set all configs from talk configurations
*
* #var array
* */
protected $config;
/*
* Pusher instance
*
* #var object
* */
public $pusher;
/**
* Connect pusher and get all credentials from config.
*
* #param \Illuminate\Contracts\Config\Repository $config
*/
public function __construct(Repository $config)
{
$this->config = $config;
$this->pusher = $this->connectPusher();
}
/**
* Make pusher connection.
*
* #param array $options
*
* #return object | bool
*/
protected function connectPusher($options = [])
{
if ($this->getConfig('broadcast.enable')) {
$appId = $this->getConfig('broadcast.pusher.app_id');
$appKey = $this->getConfig('broadcast.pusher.app_key');
$appSecret = $this->getConfig('broadcast.pusher.app_secret');
$appOptions = $this->getConfig('broadcast.pusher.options');
$newOptions = array_merge($appOptions, $options);
$pusher = new Pusher($appKey, $appSecret, $appId, $newOptions);
return $pusher;
}
return false;
}
/**
* Dispatch the job to the queue.
*
* #param \Nahid\Talk\Messages\Message $message
*/
public function transmission(Message $message)
{
if (!$this->pusher) {
return false;
}
$sender = $message->sender->toArray();
$messageArray = $message->toArray();
$messageArray['sender'] = $sender;
$this->dispatch(new Webcast($messageArray));
}
/**
* get specific config from talk configurations.
*
* #param string
*
* #return string|array|int
*/
public function getConfig($name)
{
return $this->config->get(self::CONFIG_PATH.'.'.$name);
}
}
I am trying to use VS 2017 on my typescript project. I am using the goto member and trying to navigate to methods in my current file. However, VS 2017 does not seem to filter the methods properly. In the goto I am using "m and currentfile" and for example, if I try to filter "extractData", it does not seem to filter properly.
My .ts file is as follows.
export class FooterLinksServiceSiteCore implements FooterLinksService {
/**
*
* #param {Http} private http [description]
*/
constructor(private http: Http) {
}
/**
* [LoadFooterLinks description]
* #return {Observable<FooterLink[]>} [description]
*/
get(footerValuesLink: string): Observable<FooterLink[]> {
}
/**
* [extractData description]
* #param {Response} res [description]
*/
private extractData(res: Response): Array<FooterLink> {
let mappedFooterLinks: Array<FooterLink> = new Array<FooterLink>();
let footerLinks = res.json();
footerLinks.forEach(footerLink => {
mappedFooterLinks.push(new FooterLink(footerLink.Title, footerLink.Url));
});
return mappedFooterLinks;
}
/**
* [handleError description]
* #param {Response | any} error [description]
*/
private handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
What I need to do is extract a 2D DataMatrix (bitmap) bar code and read it. I can make this work however, I have to loop through all the images on every page. This is taking a long time when I have 1000’s of pages, so I was wondering if it was possible to define a location(rectangle)of where the image(barcode) was and just extract that image?
The bar code is always i the same location.
note: I'm using Spire.Barcode from e-IceBlue
Thank you for any help.
CODE RenderFilter snippet:
public class MyRegionTextRenderFilter : RenderFilter {
/** the region to allow text from */
private RectangleJ filterRect;
public PdfImageObject image;
/**
* Constructs a filter
* #param filterRect the rectangle to filter text against. Note that this is a java.awt.Rectangle !
*/
public MyRegionTextRenderFilter(RectangleJ filterRect) {
this.filterRect = filterRect;
}
/**
* Constructs a filter
* #param filterRect the rectangle to filter text against.
*/
public MyRegionTextRenderFilter(iTextSharp.text.Rectangle filterRect)
{
this.filterRect = new RectangleJ(filterRect);
}
/**
* #see com.itextpdf.text.pdf.parser.RenderFilter#allowText(com.itextpdf.text.pdf.parser.TextRenderInfo)
*/
public override bool AllowImage(ImageRenderInfo renderInfo)
{
var matrix = renderInfo.GetImageCTM();
float left = matrix[6];
float top = matrix[7];
float width = matrix[0];
float height = matrix[4];
return filterRect.IntersectsLine(left, top, width, height);
}
}
Code calling :
RectangleJ rect = new RectangleJ(518.0f, 18.0f, 23.0f, 23.0f);
PdfReaderContentParser parser2 = new PdfReaderContentParser(pdfReader);
RenderFilter[] renderFilter = new RenderFilter[1];
renderFilter[0] = new MyRegionTextRenderFilter(rect);
FilteredTextRenderListener listener2 = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
parser2.ProcessContent(3, listener2);
The parser namespace of iText(Sharp) allows filtering of information digested by an IRenderListener implementation by using a RenderFilter:
public abstract class RenderFilter {
/**
* #param renderInfo
* #return true if the text render operation should be performed
*/
public virtual bool AllowText(TextRenderInfo renderInfo){
return true;
}
/**
*
* #param renderInfo
* #return true is the image render operation should be performed
*/
public virtual bool AllowImage(ImageRenderInfo renderInfo){
return true;
}
}
For filtering by area there already is a textual render filter, the RegionTextRenderFilter.
For your task simply copy it and add an AllowImage(ImageRenderInfo renderInfo) implementation similar to the existing AllowText(TextRenderInfo renderInfo) method.
I am new to java and JDBC usage. I am writing my first java application that connects to database. But i am getting this error when i click on th JButton that performs database creation. But i get this error:
$run:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at data.eceunnrecords.com.DBOptions.executeNonQuery(DBOptions.java:70)
at portal.eceunnrecords.com.CreateDatabase.createButtonActionPerformed(CreateDatabase.java:81)
at portal.eceunnrecords.com.CreateDatabase.access$000(CreateDatabase.java:13)
at portal.eceunnrecords.com.CreateDatabase$1.actionPerformed(CreateDatabase.java:42)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
here is my code:
$/** To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package portal.eceunnrecords.com;
import portal.eceunnrecords.com.*;
import data.eceunnrecords.com.*;
/**
*
* #author OPTHINKERS
*/
public class CreateDatabase extends javax.swing.JFrame {
/**
* Creates new form CreateDatabase
*/
public CreateDatabase() {
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() {
jLabel1 = new javax.swing.JLabel();
createdbtf = new javax.swing.JTextField();
createButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Database Name:");
createButton.setText("Create");
createButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createButtonActionPerformed(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(78, 78, 78)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(createButton)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(createdbtf, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(144, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(110, 110, 110)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(createdbtf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(createButton)
.addContainerGap(129, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String query = "Create Table "+this.createdbtf.getText()+"(REG_NO VARCHAR (10)"
+ "NOT NULL PRIMARY KEY, SURNAME VARCHAR (45) NOT NULL, FIRSTNAME VARCHAR (45) "
+ "NOT NULL, MIDDLENAME VARCHAR (45) NOT NULL, LEVEL INT NOT NULL, STATE_OF_ORIGIN "
+ "VARCHAR (25) NOT NULL, PHONE_NO INT NOT NULL, EMAIL VARCHAR (50) NOT NULL);";
DBOptions.executeNonQuery(query);
}
/**
* #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(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CreateDatabase.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 CreateDatabase().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton createButton;
private javax.swing.JTextField createdbtf;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
And here is the class DBOptions that communicates with my database:
$package data.eceunnrecords.com;
import java.sql.*;
import javax.swing.*;
public class DBOptions {
/**
* static variable con is used to hold the active connection information.
*/
public static Connection con = null;
/**
*This method is used to make a connection with the database
* #param strHost holds host name or ip address
* #param iPort holds port number
* #param strDBName holds the database name
* #param strUserName holds username to connect to server
* #param strPassword holds password to connect to server
* #return true for establishing connection and false for failure.
*/
public static boolean connect(String strHost, int iPort,String strDBName, String strUserName, String strPassword)
{
try
{
//loading mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");
//connection string
String url="jdbc:mysql://"+strHost+":"+iPort+"/"+strDBName;
//establishing connection
con=DriverManager.getConnection(url, strUserName,strPassword);
return true; //successfully connected
}
catch(Exception e)
{
return false; //connection failed
}
}
/**
* This method is used to close the database connection
* #param dbCon holds the active connection information
*/
public static void closeConnection(Connection dbCon)
{
try
{
dbCon.close(); //close connection
}
catch(Exception e)
{
}
}
/**
* This method is used to execute an sql non query
* #param sqlString holds the sql non query to be executed
* #return the number of rows affected
*/
public static int executeNonQuery(String sqlString)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeUpdate(sqlString);
//return the number of rows affected
}
catch(SQLException e)
{
//display error message
//JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Non Query Execution Failure", 1);
return -1;
}
}
/**
* This method is used to execute an sql query
* #param sqlQuery holds the sql query
* #return the ResultSet if successful. Return null on failure
*/
public static ResultSet executeSQLQuery(String sqlQuery)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeQuery(sqlQuery); //query successfully executed
}
catch(SQLException e)
{
//display error message
//JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Query Execution Failure", 1);
return null; //sql query execution failed
}
}
}
please help me...
It seems that the line that is throwing the NullPointerException is this line:
Statement stmt = con.createStatement();
If this is throwing a NullPointerException, then your static variable con must be null.
I can't see anywhere where you are creating your database connection function connect(). As far as I can see, you're getting the error because you're trying to create a table in a database when you're not connected to the database.
Alternatively, perhaps you are calling connect() in some code you've chosen not to share with us. In which case, I'd guess that you are failing to connect to the database. However, the following code within your connect() method is extremely unhelpful when it comes to finding out what went wrong:
catch(Exception e)
{
return false; //connection failed
}
There are numerous different reasons why your database connection might be failing, but silently swallowing all exceptions makes it incredibly difficult to find out what is going wrong. Add a line e.printStackTrace(); to this catch block (before the return line) and that will print out the exception that is causing the database connection to fail.
I've created a class that extends the Window SmartGWT class, and it is set to be modal. I am trying to make the Window close when a user clicks off the window. I have tried to link it up to a FocusChangedHandler with no luck. Has anyone done something like this before?
/**
* Sets up a modal Dialog box that lets the user edit attributes associated
* with the properties of the {#link LabElement} that are given.
*
* #author Therin Irwin
*/
public class EditorDialog extends Window {
final DynamicForm dyn = new DynamicForm();
final RichTextEditor richTextEditor = new RichTextEditor();
final List attrItems = new ArrayList();
/**
* Creates a new EditorDialog with a RichTextEditor and a list of
* attributes for the element.
*
* #param name the name of the element being edited.
* #param attr the List of String attributes of the element that can be
* edited.
* #param hasText true if the element supports text inside, false if not.
*/
public EditorDialog(String name, List attr, boolean hasText) {
super();
VLayout vert = new VLayout();
this.setShowMinimizeButton(false);
this.setIsModal(true);
this.setShowModalMask(true);
this.setTitle(name + " Editor");
richTextEditor.setWidth(550);
richTextEditor.setHeight(100);
richTextEditor.setPadding(5);
richTextEditor.setCanDragResize(true);
richTextEditor.setResizeFrom("B");
richTextEditor.setShowEdges(true);
if (attr == null || attr.size() == 0) {
richTextEditor.setHeight(300);
}
else {
int i = 0;
FormItem[] fi = new FormItem[attr.size()];
for (String at : attr) {
TextItem temp = new TextItem(at, at);
attrItems.add(temp);
fi[i++] = temp;
}
dyn.setFields(fi);
dyn.setPadding(5);
dyn.setTop(100);
}
if (hasText)
vert.addMember(richTextEditor);
if (!(attr == null || attr.size() == 0))
vert.addMember(dyn);
this.addItem(vert);
this.centerInPage();
this.setAutoSize(true);
}
/**
* Returns the text of the RichTextEditor.
*
* #return the text entered into the RichTextEditor.
*/
public String getRichText() {
return richTextEditor.getValue();
}
/**
* Sets the text in the RichTextEditor to String value.
*
* #param value the String to put as the contents of the RichTextEditor.
*/
public void setRichText(String value) {
richTextEditor.setValue(value);
}
/**
* Returns the List of TextItems that hold the user-entered values for
* attributes.
*
* #return the TextItems associated with each attribute, in order.
*/
public DynamicForm getFormItems() {
return dyn;
}
public TextItem getFormItem(int item) {
return (TextItem) dyn.getFields()[item];
}
}
#Therin
I guess according to your requirement, you need to implement this property of Window:
this.setDismissOnOutsideClick(true);