I am trying to create an application for composing an email message. The application prints out the To, Cc, Bcc, subject, and message from the user input when the send button is pushed. For some reasons, when the button is pushed, it gave me an error "Exception in thread "AWT-EventQueue-0"
here are my codes:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EmailWindow extends JPanel {
private JTextField to, cc, bcc, subject;
private JTextPane content;
private JButton send;
public EmailWindow() {
// Construct and add text fields for to, cc, bcc, and subject, followed
// by a Send button. You may use the createComponentWithLabel(...)
// utility method to construct a panel that includes a label and
// a text field, which can then be added to the EmailWindow panel.
// For example,
// add(createComponentWithLabel("Text", new JTextField(30));
// would add a text field next to a label with the word "Text".
add(createComponentWithLabel("to", new JTextField(30)));
add(createComponentWithLabel("cc", new JTextField(30)));
add(createComponentWithLabel("bcc", new JTextField(30)));
add(createComponentWithLabel("subject", new JTextField(30)));
// The JTextPane class supports multi-line text. For a single line
// of content text, you could use another JTextField instead.
setBackground(Color.cyan);
content = new JTextPane();
content.setPreferredSize(new Dimension(375, 200));
send = new JButton("Send");
send.addActionListener(new SendListener());
add(content);
add(send);
}
// -----------------------------------------------------------------------
// Utility method (which you may use in the constructor) that creates
// and returns a <code>JPanel</code> containing a <code>JLabel</code>
// next to an arbitrary component, such as a <code>JTextField</code>.
// -----------------------------------------------------------------------
private JPanel createComponentWithLabel(String label, Component comp) {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel(label, JLabel.RIGHT), BorderLayout.WEST);
p.add(comp, BorderLayout.CENTER);
return p;
}
// -----------------------------------------------------------------------
// Listener class to be attached to the Send button. When the button
// is pressed, the contents of the to, cc, bcc, subject, and contents
// fields will be printed to standard out.
// -----------------------------------------------------------------------
private class SendListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
System.out.println("To: " + to.getText());
System.out.println("Cc: " + cc.getText());
System.out.println("Bcc: " + bcc.getText());
System.out.println("Subject: " + subject.getText());
System.out.println("Message content: "+content.getText());
System.out.println(content.getText());
}
}
}
Main class :
import javax.swing.JFrame;
public class email {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create a frame
JFrame frame = new JFrame("Compose Message");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create an instance of EmailWindow and add it to the frame.
EmailWindow email = new EmailWindow();
frame.getContentPane().add(email);
// Set a reasonable starting size for the frame. Note that we
// do not use pack() here, since doing so with the default layout
// manager would produce a very long frame. Other layout managers
// (which will be discussed in Chapter 6) would solve this problem
// in a more flexible way.
frame.setSize(425, 400);
// Show the frame.
frame.setVisible(true);
}
}
error :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at hw6.EmailWindow$SendListener.actionPerformed(EmailWindow.java:59)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Your to, cc, bcc, subject JTextField are null .
You never initialize them , and you probably want to pass them as parameters in this part :
add(createComponentWithLabel("to", new JTextField(30)));
add(createComponentWithLabel("cc", new JTextField(30)));
add(createComponentWithLabel("bcc", new JTextField(30)));
add(createComponentWithLabel("subject", new JTextField(30)));
I would suggest :
to = new JTextField(30);
cc = new JTextField(30);
bcc = new JTextField(30);
subject = new JTextField(30);
add(createComponentWithLabel("to", to));
add(createComponentWithLabel("cc", cc));
add(createComponentWithLabel("bcc", bcc));
add(createComponentWithLabel("subject", subject));
Related
So, I've been trying to make a Celsius converter in Java using swing and got stuck on getting the input from the JTextField and parsing it into an Integer so i can perform an equation on it. If I leave it as a String I am unable to do any math operations.
I've added a private string called cValue in which I store the value of text field in, and then I have some code in the ActionListener that parses that string into an Integer.
When I run the program it opens up the window without any problems. I can type in anything in the text field, but as soon as I press the button the program exits out and I'm shown an error which I can't understand. If I move the code out of the action listener and run the program, it gives me an error.
Now, I'm pretty new to Java and am not that familiar with it yet. I wrote this using eclipse and made the UI with WindowBuilder. I've tried many things and nothing has worked so far. I appreciate any form of feedback I can get.
This is the code:
private String cValue;
private String result = "0";
private JPanel contentPane;
private JTextField celsiusField;
private JButton convertButton;
/**
* Create the frame.
*/
public CelsiusConverter() {
setDefaultCloseOperation(CelsiusConverter.EXIT_ON_CLOSE);
setBounds(100, 100, 194, 134);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblCelsius = new JLabel("Celsius");
lblCelsius.setBounds(10, 11, 61, 14);
contentPane.add(lblCelsius);
celsiusField = new JTextField();
celsiusField.setBounds(81, 8, 86, 20);
contentPane.add(celsiusField);
celsiusField.setColumns(10);
JLabel lblFahrenheit = new JLabel("Fahrenheit:");
lblFahrenheit.setBounds(10, 73, 70, 14);
contentPane.add(lblFahrenheit);
JLabel lblResult = new JLabel();
lblResult.setText(String.valueOf(result));
lblResult.setBounds(81, 73, 87, 14);
contentPane.add(lblResult);
cValue = celsiusField.getText();
convertButton = new JButton("Convert");
convertButton.setBounds(10, 39, 157, 23);
contentPane.add(convertButton);
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int parsed = Integer.parseInt(cValue);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CelsiusConverter frame = new CelsiusConverter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at learningWindowBuilder.CelsiusConverter$1.actionPerformed(CelsiusConverter.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
cValue = celsiusField.getText();
You can't invoke that statement yet because the GUI isn't even visible and the user hasn't had a chance to enter data into the text field.
You need to get the text from the text field in your ActionListener
String cValue = celsiusField.getText();
int parsed = Integer.parseInt(cValue);
I'm trying to make my program load a txt file with JFileChooser, but it doesn't seem to work. When I press the JButton, the console gives me a lot of errors. Here's the entire code so far:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.JFileChooser;
public class Sudoku extends JFrame{
JPanel mainWindow = new JPanel();
JPanel buttonWindow = new JPanel();
JPanel sudokuArea = new JPanel();
JButton load = new JButton("Load");
JButton solve = new JButton("Solve");
JTextArea sudokuGrid = new JTextArea();
Field field = new Field();
public static void main(String[] args) {
new Sudoku();
}
public Sudoku(){
super("SudokuSolver");
setSize(200,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(mainWindow);
mainWindow.setLayout(new BorderLayout());
mainWindow.add(buttonWindow, BorderLayout.SOUTH);
mainWindow.add(sudokuArea, BorderLayout.CENTER);
buttonWindow.add(load);
buttonWindow.add(solve);
sudokuArea.setLayout(new BorderLayout());
sudokuArea.add(sudokuGrid, BorderLayout.CENTER);
sudokuGrid.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
sudokuGrid.setEditable(false);
sudokuGrid.append(field.toString());
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loader();
}
public void loader(){
JFileChooser sumtin = new JFileChooser();
if(sumtin.showOpenDialog() == JFileChooser.APPROVE_OPTION)
{
File filer = sumtin.getSelectedFile();
field.fromFile(filer.getName());
sudokuGrid.setText(field.toString());
mainWindow.revalidate();
mainWindow.repaint();
}
}
} );
setVisible(true);
}
The field method is from another class called Field, but it's not really relevant (I think).
Here's what the console says:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Sudoku$1.loader(Sudoku.java:52)
at Sudoku$1.actionPerformed(Sudoku.java:45)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sour
ce)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I'm not really sure what to make of it, as I don't really know what it means. Any pointers?
EDIT: New errorcode after trying David Colers code:
Sudoku.java:49: error: method showOpenDialog in class JFileChooser cannot be app
lied to given types;
if(sumtin.showOpenDialog() == JFileChooser.APPRO
VE_OPTION)
^
required: Component
found: no arguments
reason: actual and formal argument lists differ in length
1 error
you are not handling the JFileChooser correctly for one thing.
EDIT: changed this keyword to null.
JFileChooser sumtin = new JFileChooser();
if(sumtin.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File filer = sumtin.getSelectedFile();
field.fromFile(filer.getName());
sudokuGrid.setText(field.toString());
mainWindow.revalidate();
mainWindow.repaint();
}
you missed a few steps:
first create a filechooser
JFileChooser fileChooser = new JFileChooser();
show it, and get the result
int result = fileChooser.showOpenDialog(this);
And if the user has opened a file, you can get it and do what you want
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
...
}
The code is supposed to get an order and its price and save them in their respective ArrayLists.
public class SetMenu0{
private double price;
private int size;
private String output;
private String priceOutput;
String next;
JTextField orderIn;
JTextField priceIn;
private JFrame orderInput;
JPanel txtFldPanel;
JPanel btnPanel;
ArrayList orderList = new ArrayList<String>();
ArrayList priceList = new ArrayList<Double>();
public SetMenu0()
{
orderInput = new JFrame();
orderInput.setTitle("Input Order and Price");
orderInput.setSize(200,350);
orderInput.getContentPane();
orderInput.setLayout(new BorderLayout());
orderInput.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel txtFldPanel = new JPanel();
orderIn = new JTextField(10);
priceIn = new JTextField(5);
txtFldPanel.add(orderIn);
txtFldPanel.add(priceIn);
JPanel btnPanel = new JPanel();
JButton addBtn = new JButton("ADD");
btnPanel.add(addBtn);
addBtn.addActionListener(new ButtonListener());
addBtn.setActionCommand("add");
JButton fnshBtn = new JButton("FINISH");
btnPanel.add(fnshBtn);
addBtn.addActionListener(new ButtonListener());
fnshBtn.setActionCommand("fnsh");
size = orderList.size();
Container cont = orderInput.getContentPane();
cont.add(txtFldPanel,BorderLayout.NORTH);
cont.add(btnPanel,BorderLayout.SOUTH);
orderInput.pack();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionEnter = e.getActionCommand();
if(actionEnter.equals("add"))
{
orderList.add(orderIn.getText());
priceList.add(Double.parseDouble(priceIn.getText()));
orderIn.setText("");
priceIn.setText("");
}
else if(actionEnter.equals("fnsh"))
{
orderInput.dispose();
}
}
}
public JFrame getFrame()
{
return orderInput;
}
public ArrayList getOrd()
{
return orderList;
}
public ArrayList getPri()
{
return priceList;
}
public int getSize()
{
return size;
}
}
When i press the ADD button it shows a NumberFormatException. Why is this? I could add the rest of the code from the main but why is it not saving in the ArrayList?
This is the error:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.howtodoinjava.demo.poi.SetMenu0$ButtonListener.actionPerformed(SetMenu0.java:84)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
It's probably due to this line:
priceList.add(Double.parseDouble(priceIn.getText()));
You want to make sure that priceIn text field contains a number before you try to parse the text.
You have to use (on button add click)
if(!(priceIn.isEmpty || orderIn.isEmpty)){
//Do your adding
}
This code checks if there is something in the JTextFiels
I am creating a java application which uses ObjectDB to create and maintain a set of databases. I'm currently trying to implement a DB to store user objects consisting of username and password strings. On a JFrame/swing class I have a button for creating new users, when this button is clicked, I want the following to happen:
Create (or connect to) database
Search the database to see if a user object exists with supplied username
if user already exists show a dialog message, otherwise create the user
However, when this button is clicked I get a 'User not found' error on the line which uses the results from the query object. I'm pretty sure it's because I have an empty database, however I want the code to work for the first time the program is ran, so it needs to handle an empty database. I've tried changing the code to create a new user before the query is first run, then the code works how I want it to each time the button is clicked, and it can detect whether or not a new user needs to be created.
I tried to create a 'default' or 'admin' type user so the search would work, however this means a repeat 'default' user will be created every time the program is ran, which is obviously an unwanted feature, and I can't do a query to check if the database is empty (so I could only create the default user on the first run of the program), because that is the problem I was having in the first place!
So, to anyone experienced with ObjectDB, is there a way I can handle the case where an empty database is searched?
Here's the relevant parts of my code:
public class FrameLogIn extends JFrame {
private JPanel contentPane;
private String username;
char[] password;
private static EntityManager em;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameLogIn frame = new FrameLogIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FrameLogIn() {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("user.odb");
em = emf.createEntityManager();
final JTextField txtUsername = new JTextField();
txtUsername.setFont(new Font("Segoe UI Light", Font.PLAIN, 30));
txtUsername.setHorizontalAlignment(SwingConstants.CENTER);
txtUsername.setToolTipText("username");
txtUsername.setText("");
txtUsername.setBounds(220, 30, 177, 52);
contentPane.add(txtUsername);
txtUsername.setColumns(10);
final JPasswordField passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.PLAIN, 30));
passwordField.setHorizontalAlignment(SwingConstants.CENTER);
passwordField.setBounds(220, 93, 177, 52);
contentPane.add(passwordField);
JButton btnNewUser = new JButton("New user");
btnNewUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
username = txtUsername.getText();
password = passwordField.getPassword();
System.out.println(username);
TypedQuery<Long> q = em.createQuery(
"SELECT COUNT(u) FROM User u "
+ "WHERE u.name = '" + username + "'", Long.class);
if (q.getSingleResult()>0) {
JOptionPane.showMessageDialog(contentPane.getParent(), "A user with this name already exists.");
} else {
em.getTransaction().begin();
User newUser = new User(username, password.toString());
em.persist(newUser);
em.getTransaction().commit();
JOptionPane.showMessageDialog(contentPane.getParent(), "User created.");
}
}
});
btnNewUser.setFont(new Font("Segoe WP Semibold", Font.PLAIN, 25));
btnNewUser.setBackground(Color.WHITE);
btnNewUser.setBounds(71, 175, 149, 63);
contentPane.add(btnNewUser);
}
}
and the error:
Exception in thread "AWT-EventQueue-0" [ObjectDB 2.5.3_03] SELECT COUNT(u) FROM ==> User <== u WHERE u.name = ''
javax.persistence.PersistenceException
Type User is not found (error 301)
(position 21) at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:723)
at sg.FrameLogIn$2.actionPerformed(FrameLogIn.java:113)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: com.objectdb.o.TEX: Type User is not found
at com.objectdb.o.MSG.e(MSG.java:107)
at com.objectdb.o.TRS.g(TRS.java:212)
at com.objectdb.o.SYR.q(SYR.java:259)
at com.objectdb.o.SYR.n(SYR.java:188)
at com.objectdb.o.QRC.<init>(QRC.java:152)
at com.objectdb.o.QRM.U6(QRM.java:250)
at com.objectdb.o.MST.U6(MST.java:933)
at com.objectdb.o.WRA.U6(WRA.java:293)
at com.objectdb.o.WSM.U6(WSM.java:114)
at com.objectdb.o.QRR.g(QRR.java:245)
at com.objectdb.o.QRR.f(QRR.java:154)
at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:716)
... 37 more
Thanks, also for the record i will not be storing plaintext passwords, I'm just trying to get a basic DB working before I start implementing hashed passwords.
This could happen if the entity class is not in the database yet (no instances of that class have been persisted yet), and a persistence unit is not defined.
If this seems to be the cause, either define a persistence unit or introduce the class to ObjectDB before the query, for example by:
em.getMetamodel().entity(User.class);
I am trying to design a three cascade JComboBox in JAVA:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class ThreeCascadeJComboBox {
private JComboBox combo1;
private JComboBox combo2;
private JComboBox combo3;
public static void main(String[] args) {
new ThreeCascadeJComboBox();
}
public ThreeCascadeJComboBox() {
JFrame v = new JFrame();
v.getContentPane().setLayout(new FlowLayout());
combo1 = new JComboBox();
loadCombo1();
combo1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadCombo2((String) combo1.getSelectedItem());
}
});
combo2 = new JComboBox();
loadCombo2((String) combo1.getSelectedItem());
combo2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadCombo3((String) combo2.getSelectedItem());
}
});
combo3 = new JComboBox();
loadCombo3((String) combo2.getSelectedItem());
v.getContentPane().add(combo1);
v.getContentPane().add(combo2);
v.getContentPane().add(combo3);
v.pack();
v.setVisible(true);
v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private void loadCombo1() {
combo1.addItem("letters");
combo1.addItem("numbers");
}
private void loadCombo2(String seleccionEnCombo1) {
combo2.removeAllItems();
if (seleccionEnCombo1.equals("letters")) {
combo2.addItem("A");
combo2.addItem("B");
combo2.addItem("C");
} else if (seleccionEnCombo1.equals("numbers")) {
combo2.addItem("1");
combo2.addItem("2");
combo2.addItem("3");
}
}
private void loadCombo3(String seleccionEnCombo2) {
combo3.removeAllItems();
if (seleccionEnCombo2.equals("A")) {
combo3.addItem("A-1");
combo3.addItem("A-2");
combo3.addItem("A-3");
} else if (seleccionEnCombo2.equals("B")) {
combo3.addItem("B-1");
combo3.addItem("B-2");
combo3.addItem("B-3");
} else if (seleccionEnCombo2.equals("C")) {
combo3.addItem("C-1");
combo3.addItem("C-2");
combo3.addItem("C-3");
} else if (seleccionEnCombo2.equals("1")) {
combo3.addItem("1-a");
combo3.addItem("1-b");
combo3.addItem("1-c");
} else if (seleccionEnCombo2.equals("2")) {
combo3.addItem("2-a");
combo3.addItem("2-b");
combo3.addItem("2-c");
} else if (seleccionEnCombo2.equals("3")) {
combo3.addItem("3-a");
combo3.addItem("3-b");
combo3.addItem("3-c");
}
}
}
But I get the next Exception when I select the numbers value in the jcombo1:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at es.mycompany.MyView.ThreeCascadeJComboBox.loadCombo3(ThreeCascadeJComboBox.java:78)
at es.mycompany.MyView.ThreeCascadeJComboBox.access$3(ThreeCascadeJComboBox.java:76)
at es.mycompany.MyView.ThreeCascadeJComboBox$2.actionPerformed(ThreeCascadeJComboBox.java:40)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.contentsChanged(Unknown Source)
at javax.swing.JComboBox.intervalRemoved(Unknown Source)
at javax.swing.AbstractListModel.fireIntervalRemoved(Unknown Source)
at javax.swing.DefaultComboBoxModel.removeAllElements(Unknown Source)
at javax.swing.JComboBox.removeAllItems(Unknown Source)
at es.mycompany.MyView.ThreeCascadeJComboBox.loadCombo2(ThreeCascadeJComboBox.java:63)
at es.mycompany.MyView.ThreeCascadeJComboBox.access$1(ThreeCascadeJComboBox.java:62)
at es.mycompany.MyView.ThreeCascadeJComboBox$1.actionPerformed(ThreeCascadeJComboBox.java:30)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The exception is thrown because at that point seleccionEnCombo2 is null.
You could add a check for null in the combo2 ActionListener and it will work fine:
if (combo2.getSelectedItem() != null) {
loadCombo3((String) combo2.getSelectedItem());
}
The problem is that the ActionListener for combo1 is triggering an ActionEvent for combo2 which will not have any selected item (as it is empty). You could add a check:
if (combo2.getSelectedItem() != null) {
loadCombo3((String) combo2.getSelectedItem());
}
As the other posts have mentioned, the selected value for the combo is null in some cases. This is occurring because you probably do not realize the ActionListener for combo2 is getting called twice. The first time it gets called is during the call to removeAllElements. This is where the null value is coming from. The second time is what you are assuming in your code to be the only call--this is in response to both population of the combo box as well as user interaction.
When you load the second combo box, that fires the action event for that box (because an action has taken place [actions are not limited to selection]. The 2nd combo box's actionPerformed attempts to load the 3rd combo box based on the 2nd combo box's selection, and there isn't any. That's your null pointer, the non-existent selection from the second combo box.