Keep getting Resultset closed sql Exception - java

this is the class where error happens
public class Drinks extends JFrame {
private JPanel contentPane;
private JButton button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Drinks frame = new Drinks();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Drinks() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 401, 401);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JList list = new JList();
list.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
}
private Component StringtoInt(String string) {
// TODO Auto-generated method stub
return null;
}
});
list.setBorder(new CompoundBorder(new MatteBorder(3, 3, 3, 3, (Color) new Color(0, 0, 0)), null));
list.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel lblDrink = new JLabel("Drink");
lblDrink.setFont(new Font("Tahoma", Font.PLAIN, 18));
JLabel lblIngredients = new JLabel("Ingredients");
lblIngredients.setFont(new Font("Tahoma", Font.PLAIN, 18));
button = new JButton("Back");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu frame = new MainMenu();
frame.setVisible(true);
dispose();
}
});
JTextPane textPane = new JTextPane();
textPane.setBorder(new LineBorder(new Color(0, 0, 0), 3));
Here is where i believe the problem to be as you can see there are no
existing close statements
JButton btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Connection connDrink = Connections.sqlConn();
int countDrinks = Connections.count();
System.out.println(countDrinks);
for (int j = 0; j < countDrinks; j++) {
String dk = "select DrinkID, Drink from Drinks where DrinkID = " + j + ";";
PreparedStatement pSt = connDrink.prepareStatement(dk);
ResultSet rS = pSt.executeQuery();
System.out.println(rS.getString(2));
int oi = Integer.parseInt(rS.getString(1).toString());
`//`list.add(rS.getString(2).toString(), null);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getClass().getName() + ": " + e.getMessage());
}
}
});
Always gives java.sql.SQLException: Result Set closed and I cant find where the result set is closed or if there is another error

I don't have enough points to comment, so I'll answer here.
you should try
if(rS.first())// move the cursor to the first row, true if there's a row, false otherwise
System.out.println(rS.getString(2));

Related

Assign string array to comboBox in java

I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.
import java.awt.EventQueue;
public class ExpenseManager {
private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExpenseManager window = new ExpenseManager();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExpenseManager() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
//#SuppressWarnings("unchecked")
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewUser = new JButton("New User");
btnNewUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewUserName.setVisible(true);
txtUserName.setVisible(true);
btnDone.setVisible(true);
}
});
btnNewUser.setBounds(23, 34, 89, 23);
frame.getContentPane().add(btnNewUser);
txtUserName = new JTextField();
txtUserName.setBounds(240, 63, 134, 20);
frame.getContentPane().add(txtUserName);
txtUserName.setVisible(false);
txtUserName.setColumns(10);
lblNewUserName = new JLabel("Enter New UserName");
lblNewUserName.setBounds(240, 38, 134, 14);
lblNewUserName.setVisible(false);
frame.getContentPane().add(lblNewUserName);
btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newUserName = txtUserName.getText();
if(!newUserName.isEmpty())
{
File f = new File("S:/Expense/" + newUserName);
if (f.exists() && f.isDirectory()) {
JOptionPane.showMessageDialog(null, "User already exists");
txtUserName.setText(null);
}
else{
boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
if(!success){
JOptionPane.showMessageDialog(null, "Unable to register");
}else{
JOptionPane.showMessageDialog(null, "User registered Successfully");
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
}
}
});
btnDone.setBounds(240, 103, 89, 23);
btnDone.setVisible(false);
frame.getContentPane().add(btnDone);
btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File[] directories = new File("S:/Expense/").listFiles();
for(int i = 0; i < directories.length; i++)
{
dir[i] = directories[i].getName();
}
comboBox.setVisible(true);
}
});
btnLogin.setBounds(23, 68, 89, 23);
frame.getContentPane().add(btnLogin);
comboBox = new JComboBox<Object>(dir);
comboBox.setBounds(24, 138, 72, 20);
comboBox.setSelectedIndex(1);
comboBox.setVisible(false);
frame.getContentPane().add(comboBox);
}
}
You can use setModel with DefaultComboBoxModel which take an array instead like :
comboBox.setModel(new DefaultComboBoxModel(dir));
Most of the code posted is not relevant to the question asked, so it should be removed (see MCVE).
Review the following, note the comments:
public class ExpenseManager {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ExpenseManager();
} catch (Exception e) { e.printStackTrace(); }
}
});
}
public ExpenseManager() { initialize(); }
private void initialize() {
JFrame frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null); //better use a layout manger
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setBounds(24, 138, 72, 20);
comboBox.setVisible(false);
frame.getContentPane().add(comboBox);
JButton btn = new JButton("Populate combo");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//populate combo
String[] dir = new String[5];
for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}
comboBox.setModel(new DefaultComboBoxModel<>(dir));
comboBox.setVisible(true);
btn.setEnabled(false); //disable button
}
});
btn.setBounds(23, 68, 89, 23);
frame.getContentPane().add(btn);
frame.setVisible(true);
}
}
EDIT implementation using a layout manager :
private void initialize() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setVisible(false);
frame.add(comboBox, BorderLayout.SOUTH); //using BorderLayout which is the default
JButton btn = new JButton("Populate combo");
btn.setPreferredSize(new Dimension(150,35));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//populate combo
String[] dir = new String[5];
for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}
comboBox.setModel(new DefaultComboBoxModel<>(dir));
comboBox.setVisible(true);
btn.setEnabled(false); //disable button
frame.pack(); //resize fram to fit the preferred size and layouts
}
});
frame.getContentPane().add(btn, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}

Dispose() only working once

My problem is that I have a class that when the user types out the text displayed dispose() is called, which works the first time but if you don't close the program and open it again, dispose() is called, but doesn't do anything which breaks the program.
public class TypeMenu extends JDialog {
protected final JPanel contentPanel = new JPanel();
protected static JTextField inputTxtField;
protected static JTextField textField;
protected static JTextField introTxtField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
* #param introTxtField2
* #param textField2
* #param inputTxtField2
*/
public TypeMenu(JTextField inputTxtField2, JTextField introTxtField2, JTextField textField2) {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getTextField());
contentPanel.add(getIntroTxtField());
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
}
}
protected JTextField getInputTxtField() {
if (inputTxtField == null) {
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
protected JTextField getIntroTxtField() {
if (introTxtField == null) {
introTxtField = new JTextField();
introTxtField.setHorizontalAlignment(SwingConstants.CENTER);
introTxtField.setFont(new Font("Tahoma", Font.BOLD, 15));
introTxtField.setText("Easy Mode");
introTxtField.setEditable(false);
introTxtField.setBounds(56, 11, 314, 29);
introTxtField.setColumns(10);
}
return introTxtField;
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setFont(new Font("Monospaced", Font.BOLD, 20));
textField.setBounds(10, 51, 414, 40);
}
return textField;
}
}
This is one of the child classes
public class Easy extends TypeMenu {
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Easy() {
super(inputTxtField, introTxtField, textField);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getIntroTxtField());
getString();
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
textField.selectAll();
}
}
private void getString() {
String str = textField.getText();
if (str.equals("")) {
String generator = StringGenerator.medium();
String nStr = "" + generator;
textField.setText(nStr);
}
}
}
The code that calls this class
public class StartMenu extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField introTxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
StartMenu dialog = new StartMenu();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates the dialog and creates the buttons that take the user to each variation of the game when pressed.
*/
public StartMenu() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
introTxt = new JTextField();
introTxt.setFont(new Font("Tahoma", Font.BOLD, 12));
introTxt.setHorizontalAlignment(SwingConstants.CENTER);
introTxt.setText("Start Menu\r\n");
introTxt.setEditable(false);
introTxt.setBounds(75, 11, 276, 20);
contentPanel.add(introTxt);
introTxt.setColumns(10);
}
{
JButton btnEasyButton = new JButton("Easy Mode");
btnEasyButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
new Easy().setVisible(true);
}
});
btnEasyButton.setBounds(141, 42, 140, 23);
contentPanel.add(btnEasyButton);
}
{
JButton btnMediumButton = new JButton("Medium Mode");
btnMediumButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Medium().setVisible(true);
}
});
btnMediumButton.setBounds(141, 81, 140, 23);
contentPanel.add(btnMediumButton);
}
{
JButton btnHardButton = new JButton("Hard Mode");
btnHardButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Hard().setVisible(true);
}
});
btnHardButton.setBounds(141, 120, 140, 23);
contentPanel.add(btnHardButton);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
}
your text field is static so he will have only one instance across the application.
so in the method getIntroTxtField() you have if statement that says :
if (introTxtField == null)
in the first time this condition is true but when you create the new instance this condition is false because the instance of the static field is all ready created in the first and you are adding the key listener inside the condition
so the action listener will be added only in the first creation.
if you need to keep the static because you need in other class you need to remove the == null
protected JTextField getInputTxtField() {
inputTxtField = null;
{
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
or remove the static from you field declaration static is used in
shared instace only when you are using only one instace across the
application like sessionFactory or any thing that need to be created
only one time.
you code is a lot to read but i think your problem is that you are calling the dispose() of the wrong object. may you are calling it always for the first object and you are creating a new one, and the dispose of this new dialog will never be call,Check you code may be you are creating many object and the dispose() is not called at all. make sure that you have full control of your objects instance to know if you are diposing the wanted dialog.

Set String on main frame from second frame

Hi guys im trying to set a string value on my main frame with a value generated in an other frame, but i dont quite know how to do it this is my code so far.
This is my mainframe opens the query frame where i input the data
public class InfoCd extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InfoCd frame = new InfoCd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn=null;
private JTextField verConsulta;
/**
* Create the frame.
*/
public InfoCd() {
conn=sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 753, 477);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.activeCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHacerConsulta = new JButton("Hacer Consulta");
btnHacerConsulta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Query q = new Query();
q.setVisible(true);
String userQuery = Query.getqueryField();//here is the problem im sending the value before filling it in the second frame
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(userQuery);
table.setModel(DbUtils.resultSetToTableModel(rs));
//insert delete update
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
btnHacerConsulta.setBounds(20, 388, 169, 39);
contentPane.add(btnHacerConsulta);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 0, 737, 367);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
verConsulta = new JTextField();
verConsulta.setBounds(260, 388, 359, 29);
contentPane.add(verConsulta);
verConsulta.setColumns(10);
}
}
here is the query field
public class Query extends JFrame {
private JPanel contentPane;
private static JTextField queryField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Query frame = new Query();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Query() {
setBackground(SystemColor.activeCaption);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 641, 146);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getqueryField();
dispose();
}
});
btnAceptar.setBounds(226, 52, 155, 34);
contentPane.add(btnAceptar);
JLabel lblConsulta = new JLabel("Consulta:");
lblConsulta.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 13));
lblConsulta.setBounds(69, 11, 101, 39);
contentPane.add(lblConsulta);
queryField = new JTextField();
queryField.setBounds(135, 21, 480, 20);
contentPane.add(queryField);
queryField.setColumns(10);
}
public static String getqueryField() {
return queryField.getText();
}
}

Searching an arraylist for username and password

I am creating a login window for a program. I am having trouble getting my program to search through my arraylist and return a username and then search again for a password.
public class Login extends JFrame {
public String firstName, lastName, account, birthYear, password;
Login(String fn, String ln, String acc, String by, String pw){
firstName = fn;
lastName = ln;
account = acc;
birthYear = by;
password = pw;
}
Login current;
ArrayList<Login> list= new ArrayList<Login>();
int count;
private JPanel contentPane;
private JPasswordField passwordField;
private final Action action = new SwingAction();
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("");
label.setBounds(217, 5, 212, 126);
contentPane.add(label);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i<list.size(); i++){
if (Arrays.equals(list.get(i).password.toCharArray(), textField.getText().toCharArray())){
System.out.println("found the account");
if (Arrays.equals(list.get(i).password.toCharArray(), passwordField.getPassword())){
current = list.get(i);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
overview frame = new overview();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
else{
JOptionPane.showMessageDialog(null, "Password does not match our records", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Account number not found", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
btnLogin.setAction(action);
btnLogin.setBounds(108, 186, 89, 23);
contentPane.add(btnLogin);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnRegister.setBounds(217, 186, 89, 23);
contentPane.add(btnRegister);
passwordField = new JPasswordField();
passwordField.setBounds(172, 148, 142, 20);
contentPane.add(passwordField);
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
panel.setBounds(39, 32, 335, 51);
contentPane.add(panel);
JLabel lblLogin = new JLabel("Login");
lblLogin.setFont(new Font("Verdana", Font.BOLD, 15));
panel.add(lblLogin);
lblLogin.setForeground(SystemColor.window);
lblLogin.setBackground(Color.BLUE);
JLabel lblAccountNumber = new JLabel("Account Number:");
lblAccountNumber.setBounds(49, 101, 113, 14);
contentPane.add(lblAccountNumber);
JLabel lblPassword = new JLabel("Password:\r\n");
lblPassword.setBounds(49, 151, 113, 14);
contentPane.add(lblPassword);
textField = new JTextField();
textField.setBounds(172, 98, 142, 20);
contentPane.add(textField);
textField.setColumns(10);
}
public void printLogin(Login l) {
System.out.println(l.firstName);
System.out.println(l.lastName);
System.out.println(l.account);
System.out.println(l.birthYear);
System.out.println(l.password);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Login");
putValue(SHORT_DESCRIPTION, "Login to your account");
}
public void actionPerformed(ActionEvent e) {
}
}
}
The code is supposed to run the program when the "Login" button is pressed but it currently isn't working.
Below line has a problem :
if (list.get(i).password.equals(passwordField.getPassword())){
JPasswordField#getPassword() return char[] where as you are comparing a String password with char[] that is wrong.
Try Arrays.equals() to compare arrays as follow:
Arrays.equals(list.get(i).password.toCharArray(), passwordField.getPassword());
I suggest you to use Map in place of ArrayList. Make username as key of Map.
Use
Map<String,Login> map = new HashMap<String,Login>();
instead of
ArrayList<Login> list= new ArrayList<Login>();
Map is more faster in search than ArrayList.
I hope that my notes can be helpful :
There is no main method to make the class runnable
The location of list.add(test); is not allowed there. It should be in constructor/method.

Text box cleared when receives focus

I have two text boxes and I'm not sure how or where to insert a line of code that clears the text box when it's clicked in.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class OfficeAreaCalculator extends JFrame implements ActionListener{
private JTabbedPane jtabbedPane;
private JPanel calculator;
JTextField lengthText, widthText, areaText;
public OfficeAreaCalculator(){
setTitle("Office Area Calculator");
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createcalculator();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Office", calculator);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
public void createcalculator(){
calculator = new JPanel();
calculator.setLayout( null );
JLabel lengthLabel = new JLabel("Enter the length of the office:");
lengthLabel.setBounds(12, 15, 260, 20);
calculator.add( lengthLabel );
lengthText = new JTextField();
lengthText.setBounds(180, 15, 80, 20);
calculator.add( lengthText );
JLabel widthLabel = new JLabel("Enter the width of the office:");
widthLabel.setBounds(15, 40, 260, 20);
calculator.add( widthLabel );
widthText = new JTextField();
widthText.setBounds(180, 40, 80, 20);
calculator.add( widthText );
JLabel areaLabel = new JLabel("Area of the Office is:");
areaLabel.setBounds(30, 70, 260, 20);
calculator.add( areaLabel );
areaText = new JTextField();
areaText.setBounds(150, 70, 120, 20);
areaText.setEditable(false);
calculator.add(areaText);
JButton calcarea = new JButton("Calculate");
calcarea.setBounds(20,110,110,20);
calcarea.addActionListener(this);
calcarea.setBackground(Color.white);
calculator.add(calcarea);
JButton Close = new JButton("Close");
Close.setBounds(150,110,80,20);
Close.addActionListener(this);
Close.setBackground(Color.white);
calculator.add(Close);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton)event.getSource();
String buttonLabel = button.getText();
if ("Close".equalsIgnoreCase(buttonLabel)){
Exit_pressed(); return;
}
if ("Calculate".equalsIgnoreCase(buttonLabel)){
Calculate_area(); return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void Calculate_area(){
String lengthString, widthString;
int length=0;
int width=0;
lengthString = lengthText.getText();
widthString = widthText.getText();
if (lengthString.length() < 1 || widthString.length() < 1 ){
areaText.setText("Enter All Numbers"); return;
}
length = Integer.parseInt(lengthString);
width = Integer.parseInt(widthString);
if (length != 0 || width != 0){
areaText.setText((length * width) + "");
} else{
areaText.setText("Enter All Numbers"); return;
}
}
public static void main(String[] args){
JFrame frame = new OfficeAreaCalculator();
frame.setSize(300, 200);
frame.setVisible(true);
}
}
for each textbox you can create FocusListener like this :
JTextField textfield = new JTextField();
textfield.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
textfield.setText("");
}
});
You'll need FocusListener for that. Check out this example.
Use:
lengthText = new JTextField();
lengthText.setBounds(180, 15, 80, 20);
lengthText.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
lengthText.setText("");
}
public void focusLost(FocusEvent e) {
}
});
I think it is sexier to selectAll instead of setting text to "", because the user does not loose the previous value until she presses a new digit.
lengthText = new JTextField();
lengthText.setBounds(180, 15, 80, 20);
lengthText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
lengthText.selectAll();
}
});

Categories

Resources