Get value of string in try other method - java

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

Related

How to create a JComboBox whose elements each have two different styles?

I'm creating a Java application by using Swing. It contains a JTextField with a JComboBox which contains the last entered words with the time when these words were entered. The String with the time should be in another size and color (smaller and in light grey) as the last entered words (standard style). So in each element of the JComboBox should be used two different styles. How can I do that?
Here is an example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ComboSample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ComboSample());
}
#Override
public void run() {
JFrame frm = new JFrame("Combo example");
final JTextField fld = new JTextField(20);
TextData[] data = new TextData[]{new TextData("First", new Date(System.currentTimeMillis() - 100000)),
new TextData("Second", new Date(System.currentTimeMillis() - 200000)),
new TextData("Third", new Date(System.currentTimeMillis() - 300000)),
new TextData("Fourth", new Date(System.currentTimeMillis() - 400000))};
JComboBox<TextData> cb = new JComboBox<>(data);
cb.setSelectedItem(null);
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
TextData td = (TextData) cb.getSelectedItem();
if (td != null) {
fld.setText(td.getText());
}
}
});
frm.add(fld);
frm.add(cb, BorderLayout.EAST);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private static class TextData {
private static final DateFormat FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
private final String text;
private final Date timestamp;
public TextData(String text, Date timestamp) {
this.text = text;
this.timestamp = timestamp;
}
public String getText() {
return text;
}
#Override
public String toString() {
return "<html>" + text + " <span style=\"color:#D3D3D3\"><i>" + FORMAT.format(timestamp) + "</i></span></html>";
}
}
}
An easy approach is to choose a Look and Feel for that allow to achieve that.
Another way can be to create a different JLabel with the background color that you need for every JComboBox element and add them with:
JLabel label = new JLabel("Some text");
label.setBackground(Color.grey);
label.setOpaque(true);
jComboBox.addItem(label);
JLabel anotherLabel = new JLabel("Another text");
anotherLabel.setBackground(Color.white);
anotherLabel.setOpaque(true);
jComboBox.addItem(anotherLabel);

Needing to return value from user input

a basic problem that i can't figure out, tried a lot of things and can't get it to work, i need to be able to get the value/text of the variable
String input;
so that i can use it again in a different class in order to do an if statement based upon the result
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pInterface extends JFrame {
String input;
private JTextField item1;
public pInterface() {
super("PAnnalyser");
setLayout(new FlowLayout());
item1 = new JTextField("enter text here", 10);
add(item1);
myhandler handler = new myhandler();
item1.addActionListener(handler);
System.out.println();
}
public class myhandler implements ActionListener {
// class that is going to handle the events
public void actionPerformed(ActionEvent event) {
// set the variable equal to empty
if (event.getSource() == item1)// find value in box number 1
input = String.format("%s", event.getActionCommand());
}
public String userValue(String input) {
return input;
}
}
}
You could display the window as a modal JDialog, not a JFrame and place the obtained String into a private field that can be accessed via a getter method. Then the calling code can easily obtain the String and use it. Note that there's no need for a separate String field, which you've called "input", since we can easily and simply extract a String directly from the JTextField (in our "getter" method).
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class TestPInterface {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JFrame frame = new JFrame("TestPInterface");
// JDialog to hold our JPanel
final JDialog pInterestDialog = new JDialog(frame, "PInterest",
ModalityType.APPLICATION_MODAL);
final MyPInterface myPInterface = new MyPInterface();
// add JPanel to dialog
pInterestDialog.add(myPInterface);
pInterestDialog.pack();
pInterestDialog.setLocationByPlatform(true);
final JTextField textField = new JTextField(10);
textField.setEditable(false);
textField.setFocusable(false);
JPanel mainPanel = new JPanel();
mainPanel.add(textField);
mainPanel.add(new JButton(new AbstractAction("Get Input") {
#Override
public void actionPerformed(ActionEvent e) {
// show dialog
pInterestDialog.setVisible(true);
// dialog has returned, and so now extract Text
textField.setText(myPInterface.getText());
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
// by making the class a JPanel, you can put it anywhere you want
// in a JFrame, a JDialog, a JOptionPane, another JPanel
#SuppressWarnings("serial")
class MyPInterface extends JPanel {
// no need for a String field since we can
// get our Strings directly from the JTextField
private JTextField textField = new JTextField(10);
public MyPInterface() {
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getSource();
textComp.selectAll();
}
});
add(new JLabel("Enter Text Here:"));
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = (Window) SwingUtilities.getWindowAncestor(MyPInterface.this);
win.dispose();
}
});
}
public String getText() {
return textField.getText();
}
}
A Good way of doing this is use Callback mechanism.
I have already posted an answer in the same context.
Please find it here JFrame in separate class, what about the ActionListener?.
Your method is a bit confusing:
public String userValue(String input) {
return input;
}
I guess you want to do something like this:
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
Also your JFrame is not visible yet. Set the visibility like this setVisible(true)

Spontaneous click of a button in Swing

So if a user do not press any button,the action listener is not triggered and i end up with an exception. So i thought to put a default String in my FrameClass and change that String whenever a button is clicked,than in my main class i do a loop that keeps on looping until the default String is changed,so i think it is an infinite loop. Is it okay to do that ?
package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
/**
*
* #author E-TECH
*/
public class ButtonsFrame extends JFrame {
private JButton ScPerF, weekSc, both,cancel;
private SchedulePerWeek week;
private CoursesPerWeek course;
private JPanel panel;
private String choice;
private File file;
public ButtonsFrame() {
ScPerF = new JButton("Generate schedule/faculty");
weekSc = new JButton("Generate weekly class schedule");
both = new JButton("Generate Both");
cancel = new JButton("Cancel");
choice="nothing";
ScPerF.addActionListener(new ButtonListener());
weekSc.addActionListener(new ButtonListener());
both.addActionListener(new ButtonListener());
cancel.addActionListener(new ButtonListener());
setResizable(false);
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
panel = new JPanel();
panel.add(ScPerF);
panel.add(weekSc);
panel.add(both);
panel.add(cancel);
getContentPane().add(panel);
setVisible(true);
pack();
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == ScPerF) {
dispose();
choice = "faculty";
}
if (event.getSource() == weekSc) {
dispose();
choice = "course";
}
if (event.getSource() == both) {
dispose();
choice = "both";
}
if (event.getSource()==cancel){
dispose();
choice="cancel";
}
}
}
public boolean Activated() {
return ScPerF.isSelected() || weekSc.isSelected();
}
public String getChoice() {
return choice;
}
public File getFile() {
return file;
}
}
public class SchedulePerWeek {
HSSFSheet weekSh,courseSh;
int instructor_count;
HSSFWorkbook wb;
public SchedulePerWeek() {
ExcelReader reader = new ExcelReader();
HSSFSheet sh = reader.getSortedSheet();
String choice=reader.getChoice();
if(choice.equals("cancel")||choice.equals("nothing")){///i fixed the exception with this condition by closing the program instead of continuing,but i want to wait for the user instead of just exiting the program
System.exit(1);
}
wb = new HSSFWorkbook();
/////
///more code
I ran your code from a couple of edits ago, and it works fine on my Windows 8 workstation, Java 7.
Before you go much further in your GUI design, read this answer to The Use of Multiple JFrames, Good/Bad Practice?
I modified your code to use a JFrame, rather than extend one. You should only extend a Swing component when you override one of the component methods.
You only need to define your Button listener once. You set the listener on your buttons.
I changed the JFrame default close operation to exit on close.
I added a main method so I could run your code.
Here's the code with the changes.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
/**
*
* #author E-TECH
*/
public class ButtonsFrame{
private JButton scPerf, weekSc, both, cancel;
// private SchedulePerWeek week;
// private CoursesPerWeek course;
private JFrame frame;
private JPanel panel;
private String choice;
private File file;
public ButtonsFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scPerf = new JButton("Generate schedule/faculty");
weekSc = new JButton("Generate weekly class schedule");
both = new JButton("Generate Both");
cancel = new JButton("Cancel");
choice = "nothing";
ButtonListener listener = new ButtonListener();
scPerf.addActionListener(listener);
weekSc.addActionListener(listener);
both.addActionListener(listener);
cancel.addActionListener(listener);
frame.setResizable(false);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
panel = new JPanel();
panel.add(scPerf);
panel.add(weekSc);
panel.add(both);
panel.add(cancel);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == scPerf) {
frame.dispose();
choice = "faculty";
}
if (event.getSource() == weekSc) {
frame.dispose();
choice = "course";
}
if (event.getSource() == both) {
frame.dispose();
choice = "both";
}
if (event.getSource() == cancel) {
frame.dispose();
choice = "cancel";
}
}
}
public boolean Activated() {
return scPerf.isSelected() || weekSc.isSelected();
}
public String getChoice() {
return choice;
}
public File getFile() {
return file;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonsFrame();
}
});
}
}

MVC View Error Java

I'm trying to create an Onscreen telepad where people can press the keypad buttons and itll come up in the text box I haven't made the ActionListner for the keypad yet but I want it to show up in the view... Here's the code for the Keypad Panel and the View there is also a duration timer which I've managed to get working but can't put them into one view
Here's the Keypad Panel
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class KeypadPanel extends JPanel {
private JButton noStar;
private JButton noHash;
private JButton[] buttons;
private JButton C;
private JButton add;
private JPanel keypadPanel;
public KeypadPanel(TelepadController controller) {
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("" + i);
// buttons[i].addActionListener(controller.new NumberButtonListener());
}
//noStar.addActionListener(controller.new noStarActionListener);
//noHash.addActionListener(controller.new noHashActionListener);
//C.addActionListener(controller.new CActionListener);
//add.addActionListener(controller.new addActionListener);
noStar = new JButton("*");
noHash = new JButton("#");
C = new JButton("C");
add = new JButton("+");
JPanel keypadPanel = new JPanel();
keypadPanel.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++) {
keypadPanel.add(buttons[i]);
add(noStar);
add(noHash);
add(C);
add(add);
}
}
}
And here's the code for the main View
package londontelepad2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import org.apache.commons.beanutils.BeanUtils;
public class TelepadView implements Observer {
private StopwatchPanel stopwatchPanel;
private KeypadPanel keypadPanel;
private JFrame frame;
/**
*
* #param controller
*/
public TelepadView(TelepadController controller) {
super();
this.setResources();
frame = new JFrame("London Telepad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stopwatchPanel = new StopwatchPanel(controller);
//stopwatchPanel = new StopwatchPanel2(controller);
keypadPanel = new KeypadPanel(controller);
frame.getContentPane().add(stopwatchPanel);
frame.getContentPane().add(keypadPanel);
frame.pack();
}
public void show() {
frame.setVisible(true);
}
#Override
public void update(Observable observable, Object arg) {
if (arg.equals(Properties.TIME)) {
try {
stopwatchPanel.setTime(BeanUtils.getProperty(observable,
Properties.TIME));
} catch (Exception e) {
System.out.println(e);
}
}
}
public void setResetState() {
stopwatchPanel.setButtons(true, false, false);
}
public void setStoppedState() {
stopwatchPanel.setButtons(false, false, true);
}
public void setRunningState() {
stopwatchPanel.setButtons(false, true, false);
}
private void setResources() {
ColorUIResource defaultBackground = new ColorUIResource(Color.white);
ColorUIResource defaultForeground = new ColorUIResource(Color.black);
ColorUIResource disabledColor = new ColorUIResource(Color.lightGray);
FontUIResource smallFont = new FontUIResource(
new Font("Dialog", Font.BOLD, 12));
FontUIResource bigFont = new FontUIResource(
new Font("Dialog", Font.BOLD, 14));
UIManager.put("Button.background",
defaultBackground);
UIManager.put("Button.foreground",
defaultForeground);
UIManager.put("Button.disabledText",
disabledColor);
UIManager.put("Button.font", smallFont);
UIManager.put("Label.background",
defaultBackground);
UIManager.put("Label.foreground",
defaultForeground);
UIManager.put("Label.font", bigFont);
UIManager.put("Panel.background",
defaultBackground);
UIManager.put("Panel.foreground",
defaultForeground);
}
}
If I do the .add seperately I get an error to do with (actual and formal argument lists differ in length)
and if i do it together I get java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
And I can't find what it is im doing wrong!!
All the help in the world would be very appreciated seeing as I'm an Uber noob at java!
Thank you
Bilal
UPDATE
Here's a log of the error I reciveve when I put them in the same .add field
Exception in thread "main" java.lang.NullPointerException
at londontelepad2.KeypadPanel.<init>(KeypadPanel.java:48)
at londontelepad2.TelepadView.<init>(TelepadView.java:46)
at londontelepad2.TelepadController.<init>(TelepadController.java:33)
at londontelepad2.LondonTelepad2.main(LondonTelepad2.java:19)
Java Result: 1
Wait, KeypadPanel is just a plain object. Why doesn't it extend JPanel?
you are calling the add()-method of a JFrame to add your components to the frame? You need to call
frame.getContentPane().add(comp);

Java - JFrame not displaying its contents at all

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);
}
}

Categories

Resources