I have and edit button and its supposed to open a different Jframe but for some reason it flashes on screen and goes away. I cant figure it out maybe you guys can. And my delete button deletes the row above the row selected. the frame is at like 250 and the button pressed is on line 323
Button declaration:
btnAdd = new JButton("Add Student");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false);
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false);
btnSort = new JButton("Update");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
btnAddInput = new JButton("Add Student");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
Frame declaration:
frame1 = new JFrame("Edit Student");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
Button Handler:
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Add Student")) {
txtID.setText("");
txtName.setText("");
txtMajor.setText("");
txtGPA.setText("");
txtCampus.setText("");
txtAddress.setText("");
txtPhone.setText("");
txtEmail.setText("");
txtCurrent.setText("");
txtPast.setText("");
txtFuture.setText("");
txtNotes.setText("");
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
Student student = new Student(txtID.getText(), txtName.getName(), txtMajor.getText(), txtGPA.getText(), txtCampus.getText(), txtAddress.getText(), txtPhone.getText(),txtEmail.getText(), txtCurrent.getText(), txtPast.getText(), txtFuture.getText(), txtNotes.getText());
al.add(student);
try {
Student.saveSerialized(student, txtID.getText());
} catch (IOException ex) {
Logger.getLogger(IAdvise.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (e.getActionCommand().equals("EDIT")) {
frame1.setVisible(true);
txtID.setText(data[rowIndex][0] + "");
txtName.setText(data[rowIndex][1] + "");
txtMajor.setText(data[rowIndex][2] + "");
txtGPA.setText(data[rowIndex][3] + "");
txtCampus.setText(data[rowIndex][4] + "");
txtAddress.setText(data[rowIndex][5] + "");
txtPhone.setText(data[rowIndex][6] + "");
txtEmail.setText(data[rowIndex][7] + "");
txtCurrent.setText(data[rowIndex][8] + "");
txtPast.setText(data[rowIndex][9] + "");
txtFuture.setText(data[rowIndex][10] + "");
txtNotes.setText(data[rowIndex][11] + "");
txtID.setEditable(false);
frame1.setTitle("Enter Student data");
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
data[rowNumber][5] = data[i][5];
data[rowNumber][6] = data[i][6];
data[rowNumber][7] = data[i][7];
data[rowNumber][8] = data[i][8];
data[rowNumber][9] = data[i][9];
data[rowNumber][10] = data[i][10];
data[rowNumber][11] = data[i][11];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
data[rowNumber][5] = "";
data[rowNumber][6] = "";
data[rowNumber][7] = "";
data[rowNumber][8] = "";
data[rowNumber][9] = "";
data[rowNumber][10] = "";
data[rowNumber][11] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
Basically, when you call setVisible on a frame, the code will continue running without stopping.
What this is leading to is...
frame1.setVisible(true);
.
.
.
frame1.dispose();
Basically, you make the frame visible, but later in your code, you dispose of it.
What you really want is a modal dialog which, when made visible, will block the code execution until it is closed.
Take a look at How to make dialogs for more details
Review...
Don't extend PlainDocument to perform filtering of fields, instead, use a DocumentFilter. Take a look at Text Component Features and MDP's Weblog
Don't use KeyListener on text fields to performing filter, instead, use a DocumentFilter
Don't call JTable.updateUI. This has nothing to do with updating the UI when it's contents changed and is used to update the look and feel if it changes. Instead, rely on the TableModel and raise appropriate events to tell the table to update itself
Reduce the complexity of your actionPerformed method. Try breaking the logic down into separate methods, maybe even separate ActionListeners or if you really want to try something modular and advanced, take a look at How to use Actions
I did something like you and the result is same with you ,so I can give you a method to take it,
you can get a method to print the look,and frame.setVible(true) can be make to called by a method,
create more frame,and when you want to update or repaint it,you can call a method.
I hope what I says can be make some help to you .
Related
This question is similar to this : How do you reference a button inside of its actionlistener?
I want to create a simple form containing 8 toggle buttons. if i select the toggle button and click save button, it will write into the text file i.e "Button x, On". Next time i open the form, the form will check in the notepad if Button x is already on. If on, the toggle button will already be selected and vice versa.
I know how to write to and read from the notepad, but i am not sure how to check if i.e the user select button 2 then the code will write into second line " Button2, on"
Here is my code so far to write :
Path path = Paths.get(csvFile);
// check if button x is selected, if yes : <- how to refer to button x ?
BufferedWriter bw = new BufferedWriter(New FileWriter(csvFile, true);
writer.write ("button x,on" + "\r\n");
writer.close
and this is my code when the form is opened :
BufferedReader br = null;
String line = "";
String resFilesplitby = ",";
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null){
String[] condition = line.split(csvFilesplitby);
String power = condition[1];
// check if button x is already selected
if (button x power.equals("on")){
button x.isSelected();
}
}
I manage to found a simple way to solve the problem
By adding the button to an array.
JToggleButton[] buttons = new JToggleButton[8];
buttons[0] = seat1; //this is variable name of my button.
buttons[1] = seat2;
buttons[2] = seat3;
buttons[3] = seat4;
buttons[4] = seat5;
buttons[5] = seat6;
buttons[6] = seat7;
buttons[7] = seat8;
// do the work here
for (JToggleButton btn : buttons){
if(btn.isSelected){
}
}
For simplicity I recommend that you write all of the button statuses at the same time, and write them directly as a boolean value:
//Write the state of all the buttons in a single line:
writer.write (
x1.isSelected() + "," +
x2.isSelected() + "," +
x3.isSelected() + "," +
x4.isSelected() + "," +
x5.isSelected() + "," +
x6.isSelected() + "," +
x7.isSelected() + "," +
x8.isSelected());
Then reading it back as a single line and just compare each of the 8 items split by the ",":
String[] condition = line.split(csvFilesplitby);
if (condition[0].equalsIgnoreCase("true")){
x1.setSelected(true);
}else if (condition[1].equalsIgnoreCase("true")){
x2.setSelected(true);
}else if (condition[2].equalsIgnoreCase("true")){
x3.setSelected(true);
}else if (condition[3].equalsIgnoreCase("true")){
x4.setSelected(true);
}else if (condition[4].equalsIgnoreCase("true")){
x5.setSelected(true);
}else if (condition[5].equalsIgnoreCase("true")){
x6.setSelected(true);
}else if (condition[6].equalsIgnoreCase("true")){
x7.setSelected(true);
}else if (condition[7].equalsIgnoreCase("true")){
x8.setSelected(true);
}
Obviously you should add some error checking and make sure all buttons are deselected before you set if they are selected or not. But I am sure you can work that part out.
Alternatively you can try something like below :
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;
public class Ques1 extends JFrame implements ActionListener {
private JPanel panel;
private JToggleButton[] buttons;
public Ques1() {
initComponents();
buttonswork();
}
private void initComponents() {
buttons = new JToggleButton[6];
panel = new JPanel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
for (int i = 0; i < buttons.length; i++) {
JToggleButton tb = buttons[i];
tb = new JToggleButton("tb" + (i + 1));
tb.addActionListener(this);
panel.add(tb);
}
getContentPane().add(panel);
pack();
}
private void buttonswork() {
try {
String line = "";
String buttonString = "tb1-0\n"
+ "tb2-0\n"
+ "tb3-0\n"
+ "tb4-1\n"
+ "tb5-1\n"
+ "tb6-0\n";
BufferedReader br = new BufferedReader(new StringReader(buttonString));
while ((line = br.readLine()) != null) {
Component[] components = panel.getComponents();
for (Component c : components) {
if (c instanceof JToggleButton) {
String ac = ((JToggleButton) c).getActionCommand();
((JToggleButton) c).addActionListener(this);
if (ac.equalsIgnoreCase(line.split("-")[0])) {
((JToggleButton) c).setSelected(Integer.parseInt(line.split("-")[1]) == 1);
}
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Ques1().setVisible(true);
});
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "tb1":
//do your work here ...
break;
case "tb2":
//do your work here ...
break;
}
}
}
I am currently working on an address book program, and got it to work before...
but for some reason, I cannot get the GUI window to open up on DrJava
I have tried compiling it with no errors.. I did comment out the exceptions because it was giving me problems, so I will fix that error, but that is for the FileIO anyway
It is so weird how I cannot get the GUI to popup, I am really not sure why it isn't working...
//imports
import javax.swing.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.*;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*; //Adding the event since we will now be using an action listener
import java.io.FileNotFoundException;
public class AddressbookFinal extends JFrame implements ActionListener//actionlistener enables us to set actions to buttons
{
// Create some Panels
JPanel pan1 = new JPanel ();//panel 1
JPanel pan2 = new JPanel ();//panel 2
File writeFile = new java.io.File ("Address book.txt"); //create the file to write to
File readFile = new java.io.File ("Address book.txt");//read the file
//global variables
static final int MAX = 100;//lenght of the arrays
String lastname[] = new String [MAX];//holds last names
String names[] = new String [MAX];//holds first names
String e_mail[] = new String [MAX];// holds emails
String address[] = new String [MAX];//holds addresses
String phone[] = new String [MAX];// holds phone numbers
int total;//the counter that keeps track of our position
// Create some GUI components
JLabel lastnameLabel = new JLabel ("Last name", JLabel.LEFT);
JTextField lastnameField = new JTextField (40);
JLabel nameLabel = new JLabel ("First Name ", JLabel.LEFT);
JTextField nameField = new JTextField (40);
JLabel AddressLabel = new JLabel ("Address", JLabel.LEFT);
JTextField AddressField = new JTextField (40);
JLabel PhoneLabel = new JLabel ("Phone", JLabel.LEFT);
JTextField PhoneField = new JTextField (40);
JLabel EmailLabel = new JLabel ("Email", JLabel.LEFT);
JTextField EmailField = new JTextField (40);
JButton deleteButton = new JButton ("Delete");
JButton saveButton = new JButton ("Save");
JButton modifyButton = new JButton ("Update");
JButton previousButton = new JButton ("<<");
JButton searchButton = new JButton ("Search");
JButton nextButton = new JButton (">>");
JButton readButton = new JButton ("Read");
JButton writeButton = new JButton ("Write");
JButton clearButton = new JButton ("Clear");
JLabel instructionsLabel = new JLabel ("Enter your name", JLabel.LEFT);
JButton exitButton = new JButton ("Exit");
// CONSTRUCTOR - Setup your GUI here
public void HamzaTest () throws IOException
{
total = 0;
//all fields to empty
for (int i = total ; i < names.length ; i++)
{
lastname [i] = "";
names [i] = "";
e_mail [i] = "";
address [i] = "";
phone [i] = "";
}
setTitle ("Hello World!"); // Create a window with a title
setSize (640, 480); // set the window size
// Create some Layouts
GridLayout layout1 = new GridLayout (4, 1);
GridLayout layout2 = new GridLayout (5, 1);
// Set the frame and both panel layouts
setLayout (layout1); // Setting layout for the whole frame
pan1.setLayout (layout2); // Layout for Pan1
pan2.setLayout (layout1); // Layout for Pan2
saveButton.addActionListener (this); // Add an action listener to the buttons
deleteButton.addActionListener (this);
modifyButton.addActionListener (this);
previousButton.addActionListener (this);
searchButton.addActionListener (this);
nextButton.addActionListener (this);
clearButton.addActionListener (this);
exitButton.addActionListener (this);
readButton.addActionListener (this);
writeButton.addActionListener (this);
// this allows the program to know if
// the button was pressed
// Add all the components to the panels
pan1.add (lastnameLabel);
pan1.add (lastnameField);
pan1.add (nameLabel);
pan1.add (nameField);
pan1.add (AddressLabel);
pan1.add (AddressField);
pan1.add (PhoneLabel);
pan1.add (PhoneField);
pan1.add (EmailLabel);
pan1.add (EmailField);
//panel 2 is for buttons
pan2.add (saveButton);
pan2.add (deleteButton);
pan2.add (modifyButton);
pan2.add (previousButton);
pan2.add (searchButton);
pan2.add (nextButton);
pan2.add (clearButton);
pan2.add (readButton);
pan2.add (writeButton);
pan2.add (exitButton);
pan2.add (instructionsLabel);
// add the panels to the frame and display the window
add (pan1);
add (pan2);
setVisible (true);//set the GUI window to visible
}
// ACTION LISTENER - This method runs when an event occurs
// Code in here only runs when a user interacts with a component
// that has an action listener attached to it
public void actionPerformed (ActionEvent event) /* throws IOException */
{
String command = event.getActionCommand (); // find out the name of the
// component
// that was used
if (command.equals ("Save"))
{ // if the save button was pressed
while (lastname [total] != "")//find the current position and save in the nearest
total++;
System.out.println ("save button pressed"); // display message inconsole(for testing)
System.out.println ("name:" + nameField.getText ()); // get the info located in the field component
instructionsLabel.setText ("Thank you " + nameField.getText ()); // change the label message to 'thank you'
//get the String values from the fields and set them to our arrays
lastname [total] = lastnameField.getText ();
names [total] = nameField.getText ();
e_mail [total] = EmailField.getText ();
address [total] = AddressField.getText ();
phone [total] = PhoneField.getText ();
//move to the next position
total++;
//sort the lists
Sort (lastname, names, e_mail, address, phone, total);
}
else if (command.equals ("Delete"))//if delete is pressed
{
System.out.println ("delete button pressed");
System.out.println (nameField.getText () + "was deleted");
//set the current position to empty
lastname [total] = ("");
names [total] = ("");
e_mail [total] = ("");
address [total] = ("");
phone [total] = ("");
instructionsLabel.setText ("Deleted");
}
else if (command.equals ("Update"))//modify button was pressed
{
//change a field without changing the current position meaning that it will overwrite what you already have
System.out.println (lastnameField.getText () + "was modified");
lastname [total] = lastnameField.getText ();
names [total] = nameField.getText ();
e_mail [total] = EmailField.getText ();
address [total] = AddressField.getText ();
phone [total] = PhoneField.getText ();
instructionsLabel.setText (lastnameField.getText () + " was modified");
}
else if (command.equals ("<<"))//previous button is pressed
{
if (total > 0)//go back if it's not zero
total--;
System.out.println ("name: " + names [total]);
//set the text field on the GUI to the current data
lastnameField.setText (lastname [total]);
nameField.setText (names [total]);
EmailField.setText (e_mail [total]);
AddressField.setText (address [total]);
PhoneField.setText (phone [total]);
instructionsLabel.setText (names [total]);
}
else if (command.equals ("Search"))//search for a specific name(last name)
{
int location = search (lastname, lastnameField.getText (), 0, 99);
if (location >= 0)//if the name is found the mehtod will return a number larger than zero which is the location
{
lastnameField.setText (lastname [location]);
nameField.setText (names [location]);
EmailField.setText (e_mail [location]);
PhoneField.setText (phone [location]);
AddressField.setText (address [location]);
instructionsLabel.setText ("found");
System.out.println (lastname [location]);
total = location;
}
else//the name wasn't found
instructionsLabel.setText ("not found");
}
else if (command.equals (">>"))//next button
{
if (total < 100)//move up if the position is smaller than a 100
total++;
System.out.println ("name" + names [total]);
//set the text fields to the current data
lastnameField.setText (lastname [total]);
nameField.setText (names [total]);
EmailField.setText (e_mail [total]);
AddressField.setText (address [total]);
PhoneField.setText (phone [total]);
instructionsLabel.setText (names [total]);
}
else if (command.equals ("Clear"))//clear the fields button
{
instructionsLabel.setText ("cleared");
lastnameField.setText ("");
nameField.setText ("");
EmailField.setText ("");
AddressField.setText ("");
PhoneField.setText ("");
}
else if (command.equals ("Read"))//read file that already exists
{
System.out.println ("At read");//reading
Scanner input = null;
try
{
input = new Scanner (readFile);//the file name was declared previously
while (input.hasNext ())//if there are more lines to go
{
lastname [total] = input.nextLine ();
names [total] = input.nextLine ();
e_mail [total] = input.nextLine ();
address [total] = input.nextLine ();
phone [total] = input.nextLine ();
total++;
System.out.println (total);
}
input.close ();//close the file stream
}
catch (FileNotFoundException e)//exception
{
System.out.println ("File not found");
}
//catch (IOException e)//exception
{
System.out.println ("Error writing to file");
}
//finally//makes sure the input stream is being closed
{
if (input != null)
input.close ();
}
}
else if (command.equals ("Write"))//writes to text files to save the data
{
System.out.println ("At write");
PrintWriter output = null;
try
{
output = new PrintWriter (writeFile);//the file name was declared previously
for (int i = 0 ; i < total ; ++i)//writes data to the file based on the current position
{
output.println (lastname [i]);
output.println (names [i]);
output.println (e_mail [i]);
output.println (address [i]);
output.println (phone [i]);
output.println (""); //make a space in between people
}
}
catch (IOException e)//exception
{
instructionsLabel.setText ("File cannot be read");
}
finally//makes sure the files is being closed so it would save
{
if (output != null)
output.close ();
}
instructionsLabel.setText ("Info has been saved to a file");
}
else if (command.equals ("Exit"))//exit the GUI
{
setVisible (false);//hide the GUI
}
}
public static int Search (String lastnames[], String searchString, int min, int max)//search method
{
if (max < min)
return -1;
else
{
int mid = (max + min) / 2;
if (searchString.compareToIgnoreCase (lastnames [mid]) < 0) //is below the midpoint
return Search (lastnames, searchString, min, mid - 1);
else if (searchString.compareToIgnoreCase (lastnames [mid]) > 0) //is above the midpoint
return Search (lastnames, searchString, mid + 1, max);
else
return mid; //of the searched item has been found
}
}
public static int search (String[] names, String name, int min, int max)//temporary search method
{
for (int i = 0 ; i < MAX ; i++)
{
if (names [i].compareTo (name) == 0)
return i;
}
return -1;
}
public static void Sort (String lastname[], String names[], String e_mail[], String address[], String phone[], int total)//insertion sort
{
String tempLS; //temporary variable for last names
String tempN; //temporary variable for first names
String tempA; //temporary variable for addresses
String tempP; //temporary variable for phones
String tempE; //temporary variable for emails
int j;
for (int i = 1 ; i < total ; i++) // going through list --> start i at 1
// to make one less comparison
{
tempLS = lastname [i]; // setting temp at start of loop
tempN = names [i];
tempA = address [i];
tempP = phone [i];
tempE = e_mail [i];
j = i - 1; // to check names before
while (j >= 0 && tempLS.compareToIgnoreCase (lastname [j]) < 0) // checks to see if
// previous names
// are greater ->
// then makes swap
{
lastname [j + 1] = lastname [j]; // if previous name is greater, moves
// greater value up the array by 1
names [j + 1] = names [j];
e_mail [j + 1] = e_mail [j];
address [j + 1] = address [j];
phone [j + 1] = phone [j];
j--; // compares to previous numbers
}
lastname [j + 1] = tempLS; // swap //+1 to make up for j=-1
names [j + 1] = tempN;
e_mail [j + 1] = tempE;
address [j + 1] = tempA;
phone [j + 1] = tempP;
}
}
// Main method
public static void main (String[] args) throws IOException
{
AddressbookFinal frame1 = new AddressbookFinal (); // Start the GUI
}
}
You have two choices, you either change
// CONSTRUCTOR - Setup your GUI here
public void HamzaTest() throws IOException {
to be a proper constructor for the class,
public AddressbookFinal() throws IOException {
OR you call the HamzaTest method from your main method
// Main method
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
AddressbookFinal frame1 = new AddressbookFinal(); // Start the GUI
frame1.HamzaTest();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
You should have a look at Providing Constructors for Your Classes for more details.
For the reasons for EventQueue.invokeLater, you should have a look at Concurrency in Swing
I've written a so called 'error less' code but I'm facing certain problems whilst using the application.
Here's my code:
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login implements ActionListener {
Connection conn1 = null;
Statement stmt1 = null;
Connection conn2 = null;
Statement stmt2 = null;
Connection conn3 = null;
Statement stmt3 = null;
JFrame frame = new JFrame("Login Window");
JPanel startPanel = new JPanel();
JPanel adminPanel = new JPanel();
JPanel engineerPanel = new JPanel();
JButton adminLogin = new JButton("Admin Login");
JButton engineerLogin = new JButton("Engineer Login");
JTextField adminUsername = new JTextField();
JPasswordField adminPassword = new JPasswordField();
JButton adminLog = new JButton("Login");
JButton adminBack = new JButton("Go Back");
JComboBox engineerUsername = new JComboBox();
JPasswordField engineerPassword = new JPasswordField();
JButton engineerLog = new JButton("Login");
JButton engineerBack = new JButton("Go Back");
public Login(){
//Establishing connection with database
conn1 = sqliteConnection.dbConnector();
frame.setLayout(new GridLayout(1, 1));
/*
Setting up the startPanel
*/
startPanel.setLayout(new GridLayout(3, 3, 15, 15));
// Row 1
startPanel.add(new JLabel(" "));
JLabel loginType = new JLabel(" SELECT LOGIN TYPE");
loginType.setFont(new Font("Tahoma", Font.BOLD, 12));
startPanel.add(loginType);
startPanel.add(new JLabel(" "));
// Row 2
startPanel.add(new JLabel(" "));
startPanel.add(adminLogin);
startPanel.add(new JLabel(" "));
// Row 3
startPanel.add(new JLabel(" "));
startPanel.add(engineerLogin);
startPanel.add(new JLabel(" "));
adminLogin.addActionListener(this);
engineerLogin.addActionListener(this);
/*
Setting up adminPanel
*/
adminPanel.setLayout(new GridLayout(4, 2, 15, 15));
// Row 1
adminPanel.add(new JLabel("Admin Login"));
adminPanel.add(new JLabel(" "));
// Row 2
adminPanel.add(new JLabel("Username"));
adminPanel.add(adminUsername);
// Row 3
adminPanel.add(new JLabel("Password"));
adminPanel.add(adminPassword);
// Row 4
adminPanel.add(adminLog);
adminPanel.add(adminBack);
adminLog.addActionListener(this);
adminBack.addActionListener(this);
//Initial Visibility False
adminPanel.setVisible(false);
/*
Setting up engineerPanel
*/
engineerPanel.setLayout(new GridLayout(4, 2, 15, 15));
// Row 1
engineerPanel.add(new JLabel("Engineer Login"));
engineerPanel.add(new JLabel(" "));
// Row 2
try{
Class.forName("org.sqlite.JDBC");
conn1.setAutoCommit(false);
stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery( "SELECT * FROM EngineerData;" );
List<String> engineerNamesList = new ArrayList<String>();
while ( rs1.next() ){
String name = rs1.getString("Name");
engineerNamesList.add(name);
}
// Converting array list to array
String[] engineerNames = new String[engineerNamesList.size()];
engineerNamesList.toArray(engineerNames);
// Adding array into combo-box
for (String en : engineerNames){
engineerUsername.addItem(en);
}
rs1.close();
stmt1.close();
conn1.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, e1);
}
engineerPanel.add(new JLabel("Engineer Name"));
engineerPanel.add(engineerUsername);
// Row 3
engineerPanel.add(new JLabel("Password"));
engineerPanel.add(engineerPassword);
// Row 4
engineerPanel.add(engineerLog);
engineerPanel.add(engineerBack);
engineerLog.addActionListener(this);
engineerBack.addActionListener(this);
//Initial Visibility False
engineerPanel.setVisible(false);
frame.setSize(500, 200);
frame.setResizable(false);
frame.add(startPanel);
frame.setVisible(true);
}
//Method to convert integar array list to integar array
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
//Admin login method
public void adminLogin(){
String adminUser = adminUsername.getText();
String adminPass = adminPassword.getText();
String adminUserDB = null;
String adminPassDB = null;
conn2 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn2.setAutoCommit(false);
stmt2 = conn2.createStatement();
ResultSet rs2 = stmt2.executeQuery( "SELECT * FROM AdminData;" );
adminUserDB = rs2.getString("Username");
adminPassDB = rs2.getString("Password");
conn2.close();
stmt2.close();
rs2.close();
}
catch (Exception e2){
}
if (adminUser.equals(adminUserDB) && adminPass.equals(adminPassDB)){
AdminClass ac = new AdminClass();
frame.dispose();
}
else if (adminUser.equals(adminUserDB) && adminPass != adminPassDB){
JOptionPane.showMessageDialog(null, "Incorrect Password.\nPlease enter again.");
}
else if (adminUser != adminUserDB && adminPass.equals(adminPassDB)){
JOptionPane.showMessageDialog(null, "Incorrect Username.\nPlease enter again.");
}
else if (adminUser != adminUserDB && adminPass != adminPassDB){
JOptionPane.showMessageDialog(null, "Incorrect Username and Password.\nPlease enter again.");
}
}
//Engineer login method
public void engineerLogin(){
String engineerUser = engineerUsername.getSelectedItem().toString();
String engineerPass = engineerPassword.getText();
List<String> engineerNamesList = new ArrayList<String>();
List<String> engineerPasswordsList = new ArrayList<String>();
ArrayList<Integer> uniqueIDList = new ArrayList<Integer>();
conn3 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn3.setAutoCommit(false);
stmt3 = conn3.createStatement();
ResultSet rs3 = stmt3.executeQuery( "SELECT * FROM EngineerData;" );
while ( rs3.next() ){
int uniqueId = rs3.getInt("UniqueId");
String engineerUserDB = rs3.getString("Name");
String engineerPassDB = rs3.getString("Password");
//Adding data from database to variables that exist in our code
engineerNamesList.add(engineerUserDB);
engineerPasswordsList.add(engineerPassDB);
uniqueIDList.add(uniqueId);
}
conn3.close();
stmt3.close();
rs3.close();
}
catch (Exception e3){
}
// Creating usable arrays from array lists
String[] engineerNames = new String[engineerNamesList.size()];
engineerNamesList.toArray(engineerNames);
String[] engineerPasswords = new String[engineerPasswordsList.size()];
engineerPasswordsList.toArray(engineerPasswords);
int[] uniqueIDs = convertIntegers(uniqueIDList);
for (int i = 0; i < engineerNames.length; i++){
boolean condition = (engineerUser.equals(engineerNames[i]) && engineerPass.equals(engineerPasswords[i]));
if (condition){
frame.dispose();
EngineerPanel ep = new EngineerPanel();
//This ID is the identifier of the engineer
//This will be used to generate data only for his particular project
ep.setUniqueID(uniqueIDs[i]);
break;
}
else if (i>= 1 && condition != true){
JOptionPane.showMessageDialog(null, "Incorrect Password");
continue;
}
}
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == adminLogin){
startPanel.setVisible(false);
frame.remove(startPanel);
frame.add(adminPanel);
adminPanel.setVisible(true);
}
if (e.getSource() == engineerLogin){
startPanel.setVisible(false);
frame.remove(startPanel);
frame.add(engineerPanel);
engineerPanel.setVisible(true);
}
if (e.getSource() == adminBack){
adminUsername.setText(null);
adminPassword.setText(null);
adminPanel.setVisible(false);
frame.remove(adminPanel);
frame.add(startPanel);
startPanel.setVisible(true);
}
if (e.getSource() == engineerBack){
engineerPassword.setText(null);
engineerPanel.setVisible(false);
frame.remove(engineerPanel);
frame.add(startPanel);
startPanel.setVisible(true);
}
if (e.getSource() == adminLog){
adminLogin();
}
if (e.getSource() == engineerLog){
engineerLogin();
}
}
}
So here as you can see I'm using sqlite data base. Authorisation for the engineer only works for the first engineer but now for all of them. Even if the data is right, it shows that user data is incorrect. The JOptionPane keeps on popping up even though after I keep clicking ok. After several clicks it just takes the use to the next JFrame although it said password was incorrect.
Please help!
Your logic is flawed, if I understand your problem. You do:
for (int i = 0; i < engineerNames.length; i++){
boolean condition = ...
if (condition){
// OK
} else {
// show error
}
}
So you show the error as soon as you found a mismatch between the entered information and a database row. So everything is fine for the first object, since the first row will match. But for the second object, it will show the error, since you've entered the data for the second row, and the first row will not match. And then you "continue" so you never get to the second database row.
Your logic should be:
boolean ok=false;
for (int i = 0; i < engineerNames.length; i++){
boolean condition = ...
ok |= condition;
}
if (ok){
// OK
} else {
// show error
}
The ok |= condition is a OR operator: you want to see if any row matches. Of course if ok is true, you can have a continue to avoid looking at others matches.
But really why don't you use a query with the provided name and password?
SELECT * FROM EngineerData where Name=? and Password=?
And see if you get any result.
Good afternoon. I have created an application for an introductory java course that allows a user to sort their DVD collection by title, studio, or year. The application also allows the user to add additional DVD's to their collection, thus enlarging their arrays. The code properly compiles, but there is clearly something wrong as the titles, studio, and years are mixing themselves up. To be clear, this code is from a textbook and is part of a lab that requires the use of the exact methods, packages, etc. that you see in the code. I'm not asking for advice on how to make the code more efficient (although that is welcome as I am learning), but specifically what is wrong with the code provided causing the "scramble". Here is the code I have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class DVD extends JFrame implements ActionListener
{
// construct components
JLabel sortPrompt = new JLabel("Sort by:");
JComboBox fieldCombo = new JComboBox();
JTextPane textPane = new JTextPane();
// initialize data in arrays
String title[] = {"Casablanca", "Citizen Kane", "Singin' in the Rain", "The Wizard of Oz"};
String studio[] = {"Warner Brothers", "RKO Pictures", "MGM", "MGM"};
String year[] = {"1942", "1941", "1952", "1939"};
// construct instance of DVD
public DVD()
{
super("Classics on DVD");
}
// create the menu system
public JMenuBar createMenuBar()
{
// create an instance of the menu
JMenuBar mnuBar = new JMenuBar();
setJMenuBar(mnuBar);
// construct and populate the File menu
JMenu mnuFile = new JMenu("File", true);
mnuFile.setMnemonic(KeyEvent.VK_F);
mnuFile.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuFile);
JMenuItem mnuFileExit = new JMenu("Exit");
mnuFileExit.setMnemonic(KeyEvent.VK_X);
mnuFileExit.setDisplayedMnemonicIndex(1);
mnuFile.add(mnuFileExit);
mnuFileExit.setActionCommand("Exit");
mnuFileExit.addActionListener(this);
// contruct and populate the Edit menu
JMenu mnuEdit = new JMenu("Edit", true);
mnuEdit.setMnemonic(KeyEvent.VK_E);
mnuEdit.setDisplayedMnemonicIndex(0);
mnuBar.add(mnuEdit);
JMenuItem mnuEditInsert = new JMenuItem("Insert New DVD");
mnuEditInsert.setMnemonic(KeyEvent.VK_I);
mnuEditInsert.setDisplayedMnemonicIndex(0);
mnuEdit.add(mnuEditInsert);
mnuEditInsert.setActionCommand("Insert");
mnuEditInsert.addActionListener(this);
JMenu mnuEditSearch = new JMenu("Search");
mnuEditSearch.setMnemonic(KeyEvent.VK_R);
mnuEditSearch.setDisplayedMnemonicIndex(3);
mnuEdit.add(mnuEditSearch);
JMenuItem mnuEditSearchByTitle = new JMenuItem("by Title");
mnuEditSearchByTitle.setMnemonic(KeyEvent.VK_T);
mnuEditSearchByTitle.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByTitle);
mnuEditSearchByTitle.setActionCommand("title");
mnuEditSearchByTitle.addActionListener(this);
JMenuItem mnuEditSearchByStudio = new JMenuItem("by Studio");
mnuEditSearchByStudio.setMnemonic(KeyEvent.VK_S);
mnuEditSearchByStudio.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByStudio);
mnuEditSearchByStudio.setActionCommand("studio");
mnuEditSearchByStudio.addActionListener(this);
JMenuItem mnuEditSearchByYear = new JMenuItem("by Year");
mnuEditSearchByYear.setMnemonic(KeyEvent.VK_Y);
mnuEditSearchByYear.setDisplayedMnemonicIndex(3);
mnuEditSearch.add(mnuEditSearchByYear);
mnuEditSearchByYear.setActionCommand("year");
mnuEditSearchByYear.addActionListener(this);
return mnuBar;
}
// create the content pane
public Container createContentPane()
{
// populate the JComboBox
fieldCombo.addItem("Title");
fieldCombo.addItem("Studio");
fieldCombo.addItem("Year");
fieldCombo.addActionListener(this);
fieldCombo.setToolTipText("Click the drop-down arrow to display sort fields.");
// construct and populate the north panel
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
northPanel.add(sortPrompt);
northPanel.add(fieldCombo);
// create the JTextPane and center panel
JPanel centerPanel = new JPanel();
setTabsAndStyles(textPane);
textPane = addTextToTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 200));
centerPanel.add(scrollPane);
// create Container and set attributes
Container c = getContentPane();
c.setLayout(new BorderLayout(10,10));
c.add(northPanel,BorderLayout.NORTH);
c.add(centerPanel,BorderLayout.CENTER);
return c;
}
// method to create tab stops and set font styles
protected void setTabsAndStyles(JTextPane textPane)
{
// create Tab Stops
TabStop[] tabs = new TabStop[2];
tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
tabs[1] = new TabStop(350, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
TabSet tabset = new TabSet(tabs);
// set Tab Style
StyleContext tabStyle = StyleContext.getDefaultStyleContext();
AttributeSet aset =
tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset);
textPane.setParagraphAttributes(aset, false);
// set Font styles
Style fontStyle =
StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = textPane.addStyle("regular", fontStyle);
StyleConstants.setFontFamily(fontStyle, "SansSerif");
Style s = textPane.addStyle("italic", regular);
StyleConstants.setItalic(s, true);
s = textPane.addStyle("bold", regular);
StyleConstants.setBold(s, true);
s = textPane.addStyle("large", regular);
StyleConstants.setFontSize(s, 16);
}
// method to add new text to the JTextPane
public JTextPane addTextToTextPane()
{
Document doc = textPane.getDocument();
try
{
// clear the previous text
doc.remove(0, doc.getLength());
// insert title
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
// insert detail
for (int j = 0; j<title.length; j++)
{
doc.insertString(doc.getLength(), title[j] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[j] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[j] + "\t", textPane.getStyle("regular"));
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
return textPane;
}
// event to process user clicks
public void actionPerformed(ActionEvent e)
{
String arg = e.getActionCommand();
// user clicks the sort by combo box
if (e.getSource() == fieldCombo)
{
switch(fieldCombo.getSelectedIndex())
{
case 0:
sort(title);
break;
case 1:
sort(studio);
break;
case 2:
sort(year);
break;
}
}
// user clicks Exit on the File menu
if (arg == "Exit")
System.exit(0);
// user clicks Insert New DVD on the Edit Menu
if (arg == "Insert")
{
// accept new data
String newTitle = JOptionPane.showInputDialog(null, "Please enter the new movie's title");
String newStudio = JOptionPane.showInputDialog(null, "Please enter the studio for " + newTitle);
String newYear = JOptionPane.showInputDialog(null, "Please enter the year for " + newTitle);
// enlarge arrays
title = enlargeArray(title);
studio = enlargeArray(studio);
year = enlargeArray(year);
// add new data to arrays
title[title.length-1] = newTitle;
studio[studio.length-1] = newStudio;
year[year.length-1] = newYear;
// call sort method
sort(title);
fieldCombo.setSelectedIndex(0);
}
// user clicks Title on the Search submenu
if (arg == "title")
search(arg, title);
// user clicks Studio on the Search submenu
if (arg == "studio")
search(arg, studio);
// user clicks Year on the Search submenu
if (arg == "year")
search(arg, year);
}
// method to enlarge an array by 1
public String[] enlargeArray(String[] currentArray)
{
String[] newArray = new String[currentArray.length + 1];
for (int i = 0; i<currentArray.length; i++)
newArray[i] = currentArray[i];
return newArray;
}
// method to sort arrays
public void sort(String tempArray[])
{
// loop ton control number of passes
for (int pass = 1; pass < tempArray.length; pass++)
{
for (int element = 0; element < tempArray.length - 1; element++)
if (tempArray[element].compareTo(tempArray[element + 1])>0)
{
swap(title, element, element + 1);
swap(studio, element, element + 1);
swap(year, element, element + 1);
}
}
addTextToTextPane();
}
// method to swap two elements of an array
public void swap(String swapArray[], int first, int second)
{
String hold; // temporary holding area for swap
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;
}
public void search(String searchField, String searchArray[])
{
try
{
Document doc = textPane.getDocument(); // assign text to document object
doc.remove(0,doc.getLength()); // clear previous text
// display column titles
doc.insertString(0,"TITLE\tSTUDIO\tYEAR\n",textPane.getStyle("large"));
// prompt user for search data
String search = JOptionPane.showInputDialog(null, "Please enter the "+searchField);
boolean found = false;
// search arrays
for (int i = 0; i<title.length; i++)
{
if (search.compareTo(searchArray[i])==0)
{
doc.insertString(doc.getLength(), title[i] + "\t", textPane.getStyle("bold"));
doc.insertString(doc.getLength(), studio[i] + "\t", textPane.getStyle("italic"));
doc.insertString(doc.getLength(), year[i] + "\t", textPane.getStyle("regular"));
found = true;
}
}
if (found == false)
{
JOptionPane.showMessageDialog(null, "Your search produced no results.","No results found",JOptionPane.INFORMATION_MESSAGE);
sort(title);
}
}
catch(BadLocationException ble)
{
System.err.println("Couldn't insert text.");
}
}
// main method executes at run time
public static void main(String arg[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
DVD f = new DVD();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setJMenuBar(f.createMenuBar());
f.setContentPane(f.createContentPane());
f.setSize(600,375);
f.setVisible(true);
}
}
Here is a screenshot to give you a sense of what I mean be "scrambled".
Obviously, all of the titles should be in the title column, studios in studio, and years in year.
As always, I appreciate the guidance.
The problem is this line
doc.insertString(doc.getLength(), year[j] + "\t", textPane.getStyle("regular"));
where you put a tab ("\t") after the year but instead you want a newline ("\n"). So the line becomes
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));
Do you simply miss a newline after adding the year of a DVD to the document? I.e.
doc.insertString(doc.getLength(), year[j] + "\n", textPane.getStyle("regular"));
I have a JTextField in a JApplet with a ActionListener. I compiled it using Eclipse and it works fine. But when I try to load it in a .html file using applet, the JTextField does not register/recognize the ENTER key when I press it. It seems like the ActionListener did not work. I used:
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
question = ProcessString(question);
answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
static String noAnswer;
static boolean knowAnswer = true;
// process the question string, take out non-ACSII characters, spaces, to
// lower space
public String ProcessString(String question) {
question = question.toLowerCase();
String[] words = question.split("\\s+");
question = "";
for (int wordCount = 0; wordCount < words.length; wordCount++) {
words[wordCount] = words[wordCount].replaceAll("[^A-Za-z]", "");
if (wordCount != words.length - 1)
question = question + words[wordCount] + " ";
else
question = question + words[wordCount];
// System.out.println(words[wordCount]);
}
return question;
}
public String Answer(String question) {
String answer = "";
/*
if the database know the answer (did not not know), then return the
answer. if the database does not know the answer, then recover the
answer in database.
*/
if (knowAnswer == true) {
// open the database file and search if questions matches any one in
// the
// database
Scanner sc = null;
try {
sc = new Scanner(new File("database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int answerFrequency = 0;
boolean matchFound = false;
while (sc.hasNext()) {
int questionCount = sc.nextInt();
String line = sc.nextLine();
String[] databaseLine = line.split("\\s+");
String databaseQuestion = "";
String databaseAnswer = "";
// collect words for database questions
for (int wordCount = 1; wordCount <= questionCount; wordCount++) {
if (wordCount != questionCount)
databaseQuestion = databaseQuestion
+ databaseLine[wordCount] + " ";
else
databaseQuestion = databaseQuestion
+ databaseLine[wordCount];
}
// collect words for database answer
for (int wordCount = questionCount + 2; wordCount < databaseLine.length; wordCount++) {
databaseAnswer = databaseAnswer + databaseLine[wordCount]
+ " ";
}
// if the question is found in database, print answer
if (question.equals(databaseQuestion)) {
matchFound = true;
// the current answer is more frequency than the previous
// found
// answer, reassign the current answer the find answer
if (answerFrequency < Integer
.parseInt(databaseLine[questionCount + 1])) {
answerFrequency = Integer
.parseInt(databaseLine[questionCount + 1]);
answer = databaseAnswer;
}
}
}
if (matchFound == true) {
// System.out.println(answer);
knowAnswer = true;
} else {
// System.out.println("I don't know what you mean. How should I answer your question?");
knowAnswer = false;
noAnswer = question;
answer = "I don't know how to respond. How should I answer that?";
}
sc.close();
} else if (knowAnswer == false) {
String[] word = noAnswer.split(" ");
BufferedWriter writer = null;
answer = question;
try {
writer = new BufferedWriter(
new FileWriter("database.txt", true));
writer.newLine();
writer.write(word.length + " " + noAnswer + " 1 " + answer);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
System.out.println("Cannot write to file");
}
}
answer = "I got that.";
knowAnswer = true;
}
return answer;
}
Really appreciate the help.
This seems to work for me....
public class TestApplet04 extends JApplet implements ActionListener {
private JTextField textField;
private JTextArea textArea;
private String newline;
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
// question = ProcessString(question);
// answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
}
Updated after feedback
Here's you major problem...
sc = new Scanner(new File("database.txt"));
This is going to cause you a number of problems. First of all, the applet isn't likely to have access rights to read from the client machine, so you're likely to run into a security exception. Secondly, as the previous statement may have suggested, the file ins't likely to exist on the client machine.
You need to embed this resource within the Jar of your application and use getClass().getResource("...") to gain access to it. This will return a URL, from which you can use URL#openConnection to gain access to a InputStream, which can use in your scanner.
Try adding an Action to the ActionMap and setting the InputMap up for ENTER key.
textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter" );
textField.getActionMap().put("enter", new AbstractAction() {...} );
The field will have to have focus.
I'm also a newbie to Java, but found out that JTextfield is only a single line entry.
If you want a multiline entry, you would need to use a JTextArea instead.
Hope this helps :)