First post for me. I'm a student in my first year of a comp science degree.
I was just building a basic GUI for an assignment and for some reason, which I cannot see for the life of me, one of the JFrames I have created, an instance of the Register Class displays completely blank when it is called from the Register buttons action listener in the Login Class...
I also have an individual main Class which contains the Main method and calls the Login Class. The Login Class JFrame works fine and as mentioned, the issues only occur with the Registration Class when it is called within the Login Class' Register button action listener. All other JFrames in the program work fine too.
I have attempted to call the Register Class direct from the main and it has the same issues, although I have attempted to reduce it to its most basic form and it still does not display anything aside from a blank uncolored JFrame.
Here is the code (Unfinished but working as is). I apologise for my sloppyness but I am a complete beginner.
Can anyone see what is wrong with it?
Thanks in advance!
package guitest;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Register extends JFrame{
JButton regSubmit = new JButton("Submit");
JTextField email = new JTextField();
JTextField name = new JTextField();
JTextField Address1 = new JTextField();
JTextField Address2 = new JTextField();
JPasswordField password1 = new JPasswordField();
JPasswordField password2 = new JPasswordField();
String nameTxt = email.getText();
String passTxt = password1.getText();
String info = "";
FlowLayout layout1 = new FlowLayout();
public void Reg(){
this.setTitle("La Volpe Registration");
this.setLayout(layout1);
this.add(Address1);
this.add(Address2);
this.add(email);
this.add(password1);
this.add(password2);
this.add(name);
this.add(regSubmit);
this.getContentPane().setBackground(Color.green);
this.setSize(370, 160);
regSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regSubmitActionPerformed(evt);
}
private void regSubmitActionPerformed(java.awt.event.ActionEvent evt) {
String name = email.getText();
String pass = password1.getText();
String info = "";
System.out.println("registering...");
boolean eof;
try{
// Create file
FileWriter file = new FileWriter("\\regdata.txt");
BufferedWriter out = new BufferedWriter(file);
out.write("\n"+nameTxt+", "+passTxt);
}
catch (Exception e){
}
}
});
this.setVisible(true);
}
}
And the class that links to it...
package guitest;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
* #author david
*/
public class Login {
JFrame loginFrame = new JFrame();
Register reg3 = new Register();
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear");
JButton register = new JButton ("Register with Us");
JPasswordField pass = new JPasswordField(20);
JTextField email = new JTextField(20);
JLabel em = new JLabel("Email Address: ");
JLabel pw = new JLabel("Password: ");
String pathname;
String line;
String [] records = new String [1000];
int count = 0;
FlowLayout layout1 = new FlowLayout();
public Login(){
//Adds Email label and text field
loginFrame.add(em);
loginFrame.add(email);
//Adds password label and field
loginFrame.add(pw);
loginFrame.add(pass);
//Adds buttons
loginFrame.add(submit);
loginFrame.add(clear);
loginFrame.add(register);
loginFrame.getContentPane().setBackground(Color.green);
loginFrame.setLayout(layout1);
loginFrame.setSize(370, 160);
loginFrame.setTitle("La Volpe - Login");
submit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitActionPerformed(evt);
}
private void submitActionPerformed(java.awt.event.ActionEvent evt){
String emailadd = email.getText();
String password = pass.getText();
pathname = "\\regdata.txt";
boolean eof;
try{
FileReader file = new FileReader(pathname);
BufferedReader buff = new BufferedReader(file);
eof = false; // set the eof boolean to false
while (!eof){
line = buff.readLine();
if (line == null){ // test to see if the end of file has been reached
eof = true; // if the end of file has been found set the eof Boolean to true
}
else{
// end of file not reached so move the contents of the line to the records
//array
records[count] = line;
count ++;
System.out.println(line); // print out the new line input for error checking
}
}
buff.close();
}
catch (IOException e){
System.out.println("Error -- "+ e.toString());
}
boolean notTrue = false;
for (int i = 0; i < count; i++) {
if ((!notTrue)&&((emailadd + "," + password).equals(records[i]))) {
FoodSelectionMain loggedIn = new FoodSelectionMain();
loggedIn.setVisible(true);
}
}
if (!notTrue){
JOptionPane.showInputDialog("Please check your login "
+ "and try again. If you are a new user, please "
+ "register by pressing the 'REGISTER' button");
}
}
});
// TODO add your handling code here:
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
public void clearActionPerformed(java.awt.event.ActionEvent evt){
email.setText(null);
pass.setText(null);
}
});
register.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registerActionPerformed(evt);
}
public void registerActionPerformed(java.awt.event.ActionEvent evt){
reg3.setVisible(true);
System.out.println("Register pressed");
}
});
loginFrame.setVisible(true);
}
}
Try this,
in Register class, correct the constructor name to Register() from Reg().
Keep these few Guidelines in your mind before constructing a gui app
Create an object of the subclass of the container .
Consider all the components which goes in the container as instance variables.
Set these instance variable and event handling outside the constructor in methods, (ie setComponent(), setHandler().etc) but do these method invocations from constructor.
Now in main use this...
.
EventQueue.invokeLater(new Runnable() {
public void run() {
Myframe f = new Myframe();
f.setVisible(true);
}
}
Related
So, this prog getting value car_number from data base "getReprt" method , and give name to button as value from db. Also, I need to get this value next, to action listener btn_listener for each button it s own value. But whis this code, I only get last data value, and it`s the same for each button. How can I give every actionlistener situation differnet values?
what am I doing wrong?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
public class Car2q {
private Connection con;
private ResultSet rs;
static JTextArea textArea = new JTextArea();
static login frame = new login();
static JScrollPane scrollPane = new JScrollPane();
static JSplitPane splitPane = new JSplitPane();
static JPanel panel_left = new JPanel();
static JPanel panel_right = new JPanel();
static class login extends JFrame {
public static void main(String[] args) throws Exception {
final Car2q c2q = new Car2q();
c2q.getReport();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(550, 300);
frame.setVisible(true);
frame.add(splitPane);
splitPane.setSize(550, 300);
splitPane.setLeftComponent(scrollPane);
splitPane.setLeftComponent(panel_left);
splitPane.setRightComponent(panel_right);
panel_left.setLayout(new GridLayout(0, 1, 5, 5));
panel_right.setLayout(new GridLayout(0, 2, 5, 5));
}
}
public Car2q() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("");
con.createStatement();
}
catch (Exception e) {
System.out.println("Error: " + e);
}
}
public String getReport() {
String car_number = null;
String report = null;
List car_number_list = new ArrayList<>();
try {
PreparedStatement st = null;
String query2 = "select * FROM car_register";
st = con.prepareStatement(query2);
rs = st.executeQuery();
while (rs.next()) {
car_number = rs.getString("car_number");
String gotit = rs.getString("car_number");
JButton btn = new JButton(gotit);
btn.setSize(100, 100);
panel_left.add(btn);
ActionListener actionListener = new btn_listener();
btn.addActionListener(actionListener);
}
}
catch (SQLException e) {
e.printStackTrace();
}
return car_number;
}
public class btn_listener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
Car2q c2q = new Car2q();
String car = c2q.getReport();
System.out.println(car);
}
}
}
Write your button listener like this:
public class btn_listener implements ActionListener {
private final String car_number;
public bin_listener(String car_number) {
this.car_number = car_number;
}
public void actionPerformed(ActionEvent arg0) {
System.out.println(car_number);
}
}
Then in your loop you create the ActionListener:
ActionListener actionListener = new btn_listener(car_number);
And of course to be idiomatic Java you should use carNumber and BtnListener and so on.
car_number = rs.getString("car_number");
String gotit = rs.getString("car_number");
JButton btn = new JButton(gotit);
You don't need two variables that contain the same value. You just need to set the car number as the text of the button.
Then the code in your ActionListener becomes:
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
System.out.println( button.getText() );
}
The ActionListener is now generic and can be shared by all your buttons.
So your code becomes:
ActionListener buttonListener = new CarButtonListener();
while (rs.next()) {
//car_number = rs.getString("car_number");
String gotit = rs.getString("car_number");
JButton btn = new JButton(gotit);
btn.setSize(100, 100);
panel_left.add(btn);
//ActionListener actionListener = new btn_listener();
//btn.addActionListener(actionListener);
btn.addActionListener(buttonListener);
}
This allows your code to be more efficient and use less memory since you only need a single instance of the listener.
Note I renamed your "btn_listener" class to "CarButtonListener" since:
class names should be descriptive
each word in the class name should start with an upper case character
This program uses a user input file( users.txt) and gets the username and password. If the user enters the form with the correct username and password, it should display login successful.
For some reason when i test the program with users.txt, I am getting an Arrayindex out of bound exception.
LoginFrame.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package emptyframeviewer;
/**
*
* #author ACER
*/
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/*Business P11.26 Write a program with a graphical interface that implements a login window with text
fields for the user name and password. When the login is successful, hide the login
window and open a new window with a welcome message. Follow these rules for
validating the password:
1. The user name is not case sensitive.
2. The password is case sensitive.
3. The user has three opportunities to enter valid credentials.
Otherwise, display an error message and terminate the program. When the program
starts, read the file users.txt . Each line in that file contains a username and password,
separated by a space. You should make a users.txt file for testing your program.
Business P11.27 In Exercise P11.26, the password is shown as it is typed. Browse the Swing documentation
to find an appropriate component for entering a password. Improve the
solution of Exercise P11.26 by using this component instead of a text field. Each
time the user types a letter, show a ■ character.*/
#SuppressWarnings("serial")
public class LoginFrame extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private HashMap<String, String> usernamesAndPasswords;
private JTextField usernameField;
private JTextField passwordField;
private JButton loginButton;
private JPanel loginPanel;
private JPanel welcomePanel;
private JPanel mainPanel;
private CardLayout cardLayout;
public LoginFrame() {
this.createComponents();
super.setTitle("Login Panel");
super.setSize(FRAME_WIDTH, FRAME_HEIGHT);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setVisible(true);
}
private void createComponents() {
this.mainPanel = new JPanel(new CardLayout());
this.createHashMap();
this.loginPanel = this.createLoginPanel();
this.welcomePanel = this.createWelcomePanel();
this.mainPanel.add(this.loginPanel, "LoginPanel");
this.mainPanel.add(this.welcomePanel, "WelcomePanel");
this.cardLayout = (CardLayout) this.mainPanel.getLayout();
this.cardLayout.show(this.mainPanel, "LoginPanel");
super.add(this.mainPanel);
}
private JPanel createLoginPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2));
this.loginButton = new JButton("Login");
final int TEXT_FIELD_SIZE = 10;
this.usernameField = new JTextField(TEXT_FIELD_SIZE);
this.passwordField = new JPasswordField(TEXT_FIELD_SIZE);
this.loginButton.addActionListener(new ActionListener() {
private int loginAttempts = 3;
#Override
public void actionPerformed(ActionEvent arg0) {
boolean loggedIn = false;
String inputUsername = usernameField.getText().toLowerCase();
String inputPassword = passwordField.getText();
if (this.loginAttempts == 1) {
JOptionPane.showMessageDialog(null, "Number of login attemtps exceeded. Exitting...");
System.exit(1);
}
for (Map.Entry<String, String> validUser : usernamesAndPasswords.entrySet()) {
if (inputUsername.equals(validUser.getKey().toLowerCase())) {
if (inputPassword.equals(validUser.getValue())) {
System.out.println("Login successful!");
cardLayout.show(mainPanel, "WelcomePanel");
loggedIn = true;
}
}
}
if (!loggedIn) {
this.loginAttempts -= 1;
String message = String.format("Invalid username/password. %d %s remaining", this.loginAttempts,
(this.loginAttempts > 1) ? "attempts" : "attempt");
JOptionPane.showMessageDialog(null, message, "LOGIN FAILED", JOptionPane.INFORMATION_MESSAGE);
}
}
});
panel.add(new JLabel("Username"));
panel.add(this.usernameField);
panel.add(new JLabel("Password"));
panel.add(this.passwordField);
panel.add(this.loginButton);
return panel;
}
private JPanel createWelcomePanel() {
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(new JLabel("Welcome"));
panel.add(new JButton("Change password"));
JButton logoutBtn = new JButton("Logout");
logoutBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
panel.add(logoutBtn);
return panel;
}
private void createHashMap() {
this.usernamesAndPasswords = new HashMap<String, String>();
try {
Scanner fileScanner = new Scanner(new File("usersff.txt"));
while (fileScanner.hasNextLine()) {
String[] line = fileScanner.nextLine().split(" ");
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
fileScanner.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null,
"Error: no users.txt file found. No users/passwords available to read.", "USERS.TXT NOT FOUND!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame testFrame = new LoginFrame();
}
}
test file: users.txt
John 234 Peter abc
If that is the only content in the file, please check the end of file for new line. You may also add small check.
Based on the only noticeable Array in the snippet
String[] line = fileScanner.nextLine().split(" ");
if(line.length == 2)
{
this.usernamesAndPasswords.put(line[0], line[1]);
System.out.println(line[0] + " " + line[1]);
}
There are many possibilities...
I'm currently working on a GUI where you enter your name and it tells you whether or not it has been accepted. Say that if the names "John" or "Jane" are entered then you get a "Verified" message or "Unverified" message if you type any other name. Here's what I have so far, just really unsure how to add the IF statement for detecting the certain names. Thanks.
NamePrompt.java
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
SubmitButton.java
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SubmitButton implements ActionListener {
JTextField nameInput;
public SubmitButton(JTextField textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText() + " which is allowed.");
}
}
As mentioned in another answer, this should be handled in the actionPerformed method. However, going based on what you've presented to the community, here's something that should work;
if the names are case sensitive, your modification would be as such:
public SubmitButton(JTextField textfield){
nameInput = textfield;
if (nameInput.equals("InsertCaseSensitiveName")) {
//TODO: Verified Name
} else {
//TODO: Unverified Name
}
}
if case insensitive:
public SubmitButton(JTextField textfield){
nameInput = textfield;
if (nameInput.equalsIgnoreCase("InsertCaseSensitiveName")) {
//TODO: Verified Name
} else {
//TODO: Unverified Name
}
}
To use a list:
//initialize your list (formed so backwards compatible)
List<String> valid = new java.util.concurrent.CopyOnWriteArrayList<String>();
//Within a function, add all names to the list in lowercase (java.lang.String.toLowerCase())
public SubmitButton(JTextField textfield){
nameInput = textfield;
if (valid.contains(nameInput.toLowerCase()) {
//TODO: Verified Name
} else {
//TODO: Unverified Name
}
}
References:
conditional if statements
java.lang.String.equals
java.lang.String.equalsIgnoreCase
java.lang.String.toLowerCase
java.util.List
java.util.concurrent.CopyOnWriteArrayList
The actionPerformed method is called after clicking the submit button.
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText() + " which is allowed.");
// You can store the value of whatever the user enters.
String inputName = nameInput.getText();
// And add the if statements:
if(inputName.equals("John") {
JOptionPane.showMessageDialog(frame, "Verified");
}
}
Alternatively you can create a List of Strings that contains all the names that is accepted. Example:
List<String> acceptedNames = Arrays.asList(new String[]{"John", "Jane"});
// and check
if acceptedNames.contains(inputName) {
// verified.
}
I'm trying to create a hangman program. The phrase they have to guess is "bad hair day", and they see "* * **". When the user inputs a character nothing changes. I'm not 100% sure were I am going wrong but maybe it's in the passwordlabel2 or somewhere in the loop.
Demo Class
public class SecretPhrase {
int wrong = 0; //ignore for now
String phrase = "Bad hair day"; //hidden, what the user has to guess
String hiddenPhrase = "*** **** ***"; //what the user originally sees
public void changeLetter(char input)
{
StringBuilder checker = new StringBuilder(input);
StringBuilder(hiddenPhrase);
boolean wrongGuess = true;
for (int i=0; i<phrase.length(); i++)
{
if (phrase.charAt(i) == input){
checker.setCharAt(i, input);
wrongGuess = false;
}
}
hiddenPhrase = checker.toString();
if (wrongGuess){
wrong++;
}
}
private void StringBuilder(String hiddenPhrase) {
// TODO Auto-generated method stub
}
}
UI Class
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class SecretPhraseUI extends JApplet implements ActionListener {
SecretPhrase phrase = new SecretPhrase();
JLabel passwordLabel = new JLabel("Enter a letter to guess the phrase." ); //sets label to display message
JLabel passwordLabel2 = new JLabel( phrase.hiddenPhrase ); //sets label to display message
JTextField inputBox = new JTextField(40); //sets text field
JButton runButton = new JButton("Run"); //button that starts program
Container con = getContentPane(); //gets container
public void init()
{
con.setLayout(new FlowLayout());//sets flowlayout
con.add(new JLabel()); //jlabel container
con.add(inputBox); //input box container
con.add(runButton); //run button container
con.add(passwordLabel); //password label container
con.add(passwordLabel2); //password label container
runButton.addActionListener(this);//looks to see if run is clicked
inputBox.addActionListener(this);//looks to see if input box is used
}
public void actionPerformed(ActionEvent e)
{
String userInput = inputBox.getText(); //gets input from user
}
}
You have to make label.setText("The text you want to be displayed after action") . So when you do check the char, then do passwordLabel2.setText(phrase.hiddenPhrase) if the char is guessed right. :)
Working example
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class SecretPhraseUI
extends JApplet
implements ActionListener {
SecretPhrase phrase = new SecretPhrase();
JLabel passwordLabel = new JLabel("Enter a letter to guess the phrase."); //sets label to display message
JLabel passwordLabel2 = new JLabel(
phrase.hiddenPhrase ); //sets label to display message
JTextField inputBox = new JTextField(40); //sets text field
JButton runButton = new JButton("Run"); //button that starts program
Container con = getContentPane(); //gets container
public void init() {
con.setLayout(new FlowLayout());//sets flowlayout
con.add(new JLabel()); //jlabel container
con.add(inputBox); //input box container
con.add(runButton); //run button container
con.add(passwordLabel); //password label container
con.add(passwordLabel2); //password label container
runButton.addActionListener(this);//looks to see if run is clicked
inputBox.addActionListener(this);//looks to see if input box is used
}
public void actionPerformed(ActionEvent e) {
if (!inputBox.getText().isEmpty()) {
phrase.changeLetter(
inputBox.getText().charAt(0)); //gets input from user
passwordLabel2.setText(phrase.hiddenPhrase);
}
}
}
public class SecretPhrase {
int wrong = 0; //ignore for now
String phrase = "Bad hair day"; //hidden, what the user has to guess
String hiddenPhrase = "*** **** ***"; //what the user originally sees
public void changeLetter(char input) {
StringBuilder checker = new StringBuilder(hiddenPhrase);
boolean wrongGuess = true;
for (int i=0; i<phrase.length(); i++) {
if (phrase.charAt(i) == input){
checker.setCharAt(i, input);
wrongGuess = false;
}
}
hiddenPhrase = checker.toString();
if (wrongGuess){
wrong++;
}
}
}
It doesn't look like you've done anything with the user input. You could do something with the user input. Append the user input to another String and use the setText method of a label to update a label with the user input.
I have created simple gui application using JFilechooser for opening a pdf file. The gui has a browse button and a textArea to visualize the contents of the file.
I have created two classes: Gui(contains main()) and GuiJFrame to implement the gui, handlers and listeners. I have managed to get the window app but the browse button doesn't seem to work. I don't know where I have made a mistake, please help me
import java.awt.EventQueue;
public class Gui {
/** Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gui window = new Gui();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** Create the application. */
public Gui() {
initialize();
}
/** Initialize the contents of the frame. */
private void initialize() {
GuiJFrame guiJFrame = new GuiJFrame();
guiJFrame.setVisible(true);
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class GuiJFrame extends JFrame {
private JButton btnBrowse;
private JTextArea log, filtered_log;
public GuiJFrame() {
this.setTitle("TikaExtractorGui");
this.setBounds(100, 100, 700, 800);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel panel_1 = new JPanel();
this.getContentPane().add(panel_1, BorderLayout.NORTH);
JPanel panel_2 = new JPanel();
this.getContentPane().add(panel_2, BorderLayout.CENTER);
/*
* BUTTONS *
*/
JButton btnBrowse = new JButton("Browse");
panel_1.add(btnBrowse);
/*
* Text_Areas*
*/
JTextArea log = new JTextArea(50, 30);
panel_2.add(log);
log.setEditable(false);
/*
* LAYOUT *
*/
setLayout(new FlowLayout());
add(panel_1, FlowLayout.CENTER);
add(panel_2, FlowLayout.LEFT);
JScrollPane logScrollPane1 = new JScrollPane(log);
logScrollPane1.setSize(300, 300);
add(logScrollPane1);
/*
* Setting the handlers *
*/
ActionHandler a_handler = new ActionHandler();
btnBrowse.addActionListener(a_handler);
}
private class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
TikaExtractorInterface ex = new TikaExtractor();
PDFParser parser = new PDFParser();
String g = null;
if (event.getSource() == btnBrowse) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(log);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file.getName().endsWith("pdf")) {
file.getPath();
if (file != null) {
try {
g = ex.extractFromFile(parser, file);
log.setText(g);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
I know why it is not working.
Change
/* BUTTONS *
* */
JButton btnBrowse = new JButton("Browse");
panel_1.add(btnBrowse);
to
/* BUTTONS *
* */
btnBrowse = new JButton("Browse");
panel_1.add(btnBrowse);
this:
if(event.getSource() == btnBrowse)
should be
if(event.getSource().equals(btnBrowse))
You can't use the == to identify an equal object in java, you always have to use equals() to make sure that two objects are the same.
This:
JButton btnBrowse = new JButton("Browse");
should be
btnBrowse = new JButton("Browse");
You are shadowing your class member variable with a local one so the if clause always comapres against a null value. The btnBrowse is never stored in your class.
I would say add a System.out.println at the entry of actionPerformed method and check if that is being called indeed.
Also its better to use action commands for each button, so that you don't have to check for equality of event source. Something like this:
btnBrowse.setActionCommand("Browse"); //before attaching the listener
and then in the actionPerformed
String actionCommand = event.getActionCommand();
if("Browse".equals(actionCommand)) {
JFileChooser fileChooser = new JFileChooser();
int retVal = fileChooser.showOpenDialog(null);
}
Browse button should be given as argument for filechooser.
int returnVal = fc.showOpenDialog(log);
should be,
int returnVal = fc.showOpenDialog(btnBrowse);