I have the following code which reads names from the test file, which works fine
public class Names {
Scanner scan;
static String Firstname;
static String Surname;
static String Fullname;
public void OpenFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
public void ReadFile()
{
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
Fullname = Firstname + " " + Surname;
System.out.println(Fullname);
}
}
public void CloseFile()
{
scan.close();
}
}
Then I have this main class which calls the Names class. it works fine apart from it only shows the last names from the test file.
public class NameSwing implements ActionListener {
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
static String fullName;
public NameSwing(){
f.add(new JLabel("Name"));
tf.setEditable(true);
f.add(tf);
b.addActionListener(this);
f.add(b);
f.setLayout(new FlowLayout());
f.setSize(300,100);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
Names t = new Names();
t.OpenFile();
t.ReadFile();
t.CloseFile();
fullName = Names.Fullname;
}
}
This is the test file content.
Nick Harris
Olly Dean
Emma Sammons
Henry Blackwell
How can I get the textarea to show all of the names from the reader, and not just the last name?
Throw out your Names class as it isn't very helpful and over-uses static fields to its detriment. The best solution in my mind is to:
Create a File that holds your text file
Create a FileReader object with this File
Use this to create a BufferedReader object
call the JTextArea's read(...) method passing in the BufferedReader
And your done.
i.e., in actionPerformed:
BufferedRead buffReader = null;
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
buffReader = new BufferedReader(fileReader);
tf.read(buffReader, "file.txt");
} catch (WhateverExceptionsNeedToBeCaught e) {
e.printStackTrace();
} finally {
// close your BufferedReader
}
You are using too many static fields for no good reasons. Always use
static fields if you intend to make your class a Factory Class, which
in this case is not appropriate.
You are breaking the fundamental rule of encapsulation, by providing each method with a public Access Specifier, without the need of it.
Instead of calling setSize(), you can simply use pack(), which can determine the dimensions of the Container, in a much better way, than the arbitrary values you had specified.
Please do read about Concurrency in Swing, since appears to me your knowledge is a bit short on that front.
Please do learn Java Naming Conventions.
Moreover, you can simply use a StringBuilder Class, to do this thingy for you. Have a look at the modified code of yours. Do ask anything that is beyond your grasp, I be happy to help on that.
MODIFIED CODE :
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSwing implements ActionListener {
private Names t;
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
public NameSwing(){
performFileRelatedTask();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setBorder(BorderFactory.createLineBorder(Color.BLUE.darker(), 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(5, 5));
centerPanel.add(new JLabel("Name", JLabel.CENTER), BorderLayout.PAGE_START);
tf.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
tf.setEditable(true);
centerPanel.add(tf, BorderLayout.CENTER);
scroller.setViewportView(centerPanel);
JPanel footerPanel = new JPanel();
b.addActionListener(this);
footerPanel.add(b);
contentPane.add(scroller, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
f.setContentPane(contentPane);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
private void performFileRelatedTask()
{
t = new Names();
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(t.getFullNames().toString());
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new NameSwing();
}
});
}
}
class Names {
private Scanner scan;
private String firstname;
private String surname;
private StringBuilder fullnames;
public Names()
{
fullnames = new StringBuilder();
openFile();
readFile();
closeFile();
}
public StringBuilder getFullNames()
{
return fullnames;
}
private void openFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
private void readFile()
{
while(scan.hasNext())
{
firstname = scan.next();
surname = scan.next();
fullnames.append(firstname + " " + surname + "\n");
}
}
private void closeFile()
{
scan.close();
}
}
The problem is at line
Fullname = Firstname + " " + Surname;.
Make it
Fullname += Firstname + " " + Surname; + "\n"
You problem is solved :)
Here you need the change
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
//Assigning each time instead of append
Fullname = Firstname + " " + Surname;
}
Here is complete fix:
public class NameSwing implements ActionListener {
private JTextArea textArea = new JTextArea(20, 20);
private JFrame frame = new JFrame("Names");
private JButton btnView = new JButton("View");
private Scanner scanner;
private String firstName;
private String surName;
private String fullName;
public NameSwing() {
frame.add(new JLabel("Name"));
textArea.setEditable(true);
frame.add(textArea);
btnView.addActionListener(this);
frame.add(btnView);
frame.setLayout(new FlowLayout());
frame.setSize(300, 100);
frame.setVisible(true);
}
public void OpenFile() {
try {
scanner = new Scanner(new File("test.txt"));
System.out.println("File found!");
} catch (Exception e) {
System.out.println("File not found");
}
}
public void ReadFile() {
while (scanner.hasNext()) {
firstName = scanner.next();
surName = scanner.next();
// assign first time
if( fullName == null ) {
fullName = firstName + " " + surName;
} else {
fullName = fullName + "\n" + firstName + " " + surName;
}
System.out.println(fullName);
}
}
public void CloseFile() {
scanner.close();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnView) {
textArea.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
nameSwing.OpenFile();
nameSwing.ReadFile();
nameSwing.CloseFile();
}
}
Related
I modified some code I found to display a local variable instead of set text inside of a JFrame, but I'm unable to find a way to change the size of the text. I keep reading about frameName.setFont(new Font(____)), but that doesn't seem to be working for the println. How would I modify the text size? Here's my current code. (P.S. I'm new, so I'm sorry that i don't know what I'm talking about.)
import java.util.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.time.*;
import java.time.temporal.*;
public class Window {
LocalDate today = LocalDate.now();
// LocalDate bday = LocalDate.of(2018, Month.MAY, 13);
LocalDate bday = LocalDate.parse("2018-05-13");
Period until = Period.between(today, bday);
long untilDay = ChronoUnit.DAYS.between(today, bday);
String string = new String("There are " + until.getYears() + " years, " + until.getMonths() +
" months, and " + until.getDays() +
" days left! (" + untilDay + " days total)");
public static void main(String[] args) {
new Window();
}
public Window() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
CapturePane capturePane = new CapturePane();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(capturePane);
frame.setSize(1000, 1000);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
PrintStream ps = System.out;
System.setOut(new PrintStream(new StreamCapturer("STDOUT", capturePane, ps)));
// System.out.println("Hello, this is a test");
System.out.println(string);
}
});
}
public class CapturePane extends JPanel implements Consumer {
private JTextArea output;
public CapturePane() {
setLayout(new BorderLayout());
output = new JTextArea();
add(new JScrollPane(output));
}
#Override
public void appendText(final String text) {
if (EventQueue.isDispatchThread()) {
output.append(text);
output.setCaretPosition(output.getText().length());
} else {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
appendText(text);
}
});
}
}
}
public interface Consumer {
public void appendText(String text);
}
public class StreamCapturer extends OutputStream {
private StringBuilder buffer;
private String prefix;
private Consumer consumer;
private PrintStream old;
public StreamCapturer(String prefix, Consumer consumer, PrintStream old) {
this.prefix = prefix;
buffer = new StringBuilder(128);
buffer.append("[").append(prefix).append("] ");
this.old = old;
this.consumer = consumer;
}
#Override
public void write(int b) throws IOException {
char c = (char) b;
String value = Character.toString(c);
buffer.append(value);
if (value.equals("\n")) {
consumer.appendText(buffer.toString());
buffer.delete(0, buffer.length());
buffer.append("[").append(prefix).append("] ");
}
old.print(c);
}
}
}
In about Line 55:
output = new JTextArea();
output.setFont ((output.getFont()).deriveFont (24.0f));
you could modify the font size to a new float value.
See the doc for JTextArea for the method setFont, look where it is defined in the inheritance hierarchy. Look into the Font class, what to do with it.
The following code should read a list of students and their grades from a file, compare them to each other then display the student with the highest average
public class CSDept implements Comparable{
private String studentName;
private double java;
private double dataStructure;
private double algorithms;
private int numStudents;
public CSDept(){
}
public CSDept(String studentName,double java,double dataStructure,double algorithms){
this.studentName=studentName;
this.java=java;
this.dataStructure=dataStructure;
this.algorithms=algorithms;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getJava() {
return java+" ";
}
public void setJava(double java) {
this.java = java;
}
public String getDataStructure() {
return dataStructure+" ";
}
public void setDataStructure(double dataStructure) {
this.dataStructure = dataStructure;
}
public String getAlgorithms() {
return algorithms+" ";
}
public void setAlgorithms(double algorithms) {
this.algorithms = algorithms;
}
public int getNumStudents() {
return numStudents;
}
public double getAvg(){
return (java+algorithms+dataStructure)/3;
}
public int compareTo(Object student) {
if(this.getAvg()>((CSDept)student).getAvg()) return 1;
if (this.getAvg()<((CSDept)student).getAvg()) return -1;
return 0;
}
public String toString(){
return studentName+":\n"+"\t"+"Java: "+java+"\t"+"Data Structure : "+dataStructure+"\t"+"Algorithms: "+algorithms+"\n";
}}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class CSDeptFrame extends JFrame{
private JPanel pnlInput=new JPanel(new GridLayout(4,2));
private JPanel pnlOutput=new JPanel(new BorderLayout());
private JPanel pnlFinal=new JPanel(new GridLayout(1,2));
private TitledBorder brdInput=new TitledBorder("Marks");
private TitledBorder brdOutput=new TitledBorder("First Student");
private JLabel lblName=new JLabel("Student Name");
private JLabel lblJava=new JLabel("Java");
private JLabel lblDataStructure=new JLabel("Data Structure");
private JLabel lblAlgorithm=new JLabel("Algorithm");
static JLabel lblFirst=new JLabel("The First Student is :");
static JTextField txtName=new JTextField(20);
static JTextField txtJava=new JTextField(20);
static JTextField txtDataStructure=new JTextField(20);
static JTextField txtAlgorithm=new JTextField(20);
static JButton btnFirst=new JButton("Who is The First Student?");
public CSDeptFrame(String title){
super(title);
pnlInput.setBorder(brdInput);
pnlInput.add(lblName);
pnlInput.add(txtName);
pnlInput.add(lblJava);
pnlInput.add(txtJava);
pnlInput.add(lblDataStructure);
pnlInput.add(txtDataStructure);
pnlInput.add(lblAlgorithm);
pnlInput.add(txtAlgorithm);
pnlOutput.setBorder(brdOutput);
pnlOutput.add(btnFirst,BorderLayout.NORTH);
pnlOutput.add(lblFirst,BorderLayout.SOUTH);
pnlFinal.add(pnlInput);
pnlFinal.add(pnlOutput);
setLayout(new BorderLayout());
add(pnlFinal);}
public static void main(String[] args){
CSDeptFrame frame=new CSDeptFrame("CS DEPT");
frame.setSize(450,200);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
final ArrayList<CSDept> cS= new ArrayList();
File readFile =new File("read.txt");
final File writeFile=new File("write.txt");
try {
Scanner scan=new Scanner(readFile);
while(scan.hasNext()){
CSDept student=new CSDept();
student.setStudentName(scan.next());
student.setJava(scan.nextDouble());
student.setDataStructure(scan.nextDouble());
student.setAlgorithms(scan.nextDouble());
cS.add(student);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "OPS! File is not found");
}
btnFirst.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CSDept firstStudent=new CSDept();
firstStudent.setStudentName(cS.get(0).getStudentName());
firstStudent.setJava(Double.parseDouble(cS.get(0).getJava()));
firstStudent.setDataStructure(Double.parseDouble(cS.get(0).getDataStructure()));
firstStudent.setAlgorithms(Double.parseDouble(cS.get(0).getAlgorithms()));
for (int i=0;i<cS.size();i++){
if (cS.get(i).compareTo(cS.get(i+1))==-1){
firstStudent=cS.get(i+1);
}
}
txtName.setText(firstStudent.getStudentName());
txtJava.setText(firstStudent.getJava());
txtDataStructure.setText(firstStudent.getDataStructure());
txtAlgorithm.setText(firstStudent.getAlgorithms());
lblFirst.setText("The First Student is: "+ txtName.getText());
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(writeFile,true)));
for (CSDept cs: cS){
out.println(cs.toString());
out.print("The first student is " + firstStudent.toString());
}
out.close();
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "OPS! File in Not Found");
}
}
});
}}
But the problem is that the following statements don't add any objects to the arraylist, what's the problem with it?
try {
Scanner scan=new Scanner(readFile);
while(scan.hasNext()){
CSDept student=new CSDept();
student.setStudentName(scan.next());
student.setJava(scan.nextDouble());
student.setDataStructure(scan.nextDouble());
student.setAlgorithms(scan.nextDouble());
cS.add(student);
}
You problem is that you are trying to get an element at a specific index from an empty list:
final ArrayList<CSDept> cS= new ArrayList();
// ...
public void actionPerformed(ActionEvent e) {
// ...
firstStudent.setStudentName(cS.get(0).getStudentName()); // ArrayList cS is empty here
// ...
Maybe you could add a check to make sure the list is not empty before accessing the elements:
public void actionPerformed(ActionEvent e) {
if(!cS.isEmpty()) {
// do stuff
}
The reason your list is empty could be that you are reading an empty file "read.txt" so your while loop condition is never true
Scanner scan=new Scanner(readFile); // this text file is probably empty
while(scan.hasNext()){ // which makes this condition always false so loop is never executed
CSDept student=new CSDept();
student.setStudentName(scan.next());
student.setJava(scan.nextDouble());
student.setDataStructure(scan.nextDouble());
student.setAlgorithms(scan.nextDouble());
cS.add(student);
}
Furthermore, you have an ArrayIndexOutOfBoundsException risk in the for loop inside actionPerformed(). You compare current element with the next element which will, once i corresponds to the index of the last element, give an AIOBE in the comparison statement with element at index i + 1:
for (int i=0;i<cS.size();i++){
if (cS.get(i).compareTo(cS.get(i+1))==-1){ // once i = cS.size() - 1, you will get an AIOBE here
firstStudent=cS.get(i+1);
}
}
You can fix this by starting the loop at i = 1 and comparing with element at i - 1 or use a forEach loop which is a cleaner way of achieving this since it doesn't involve indexed access.
I have a problem with my GUI code that I just can't get my head around it and it concerns file writing with GUI Frames.
You see with my code below, I can Add, Remove and Display person Objects with a JTable. The problem I have is writing each attribute of each object to a file named "PersonList.txt".
The annoying thing about this is that supposing I manually put values into the file, my code is able to read each line and create person objects with the values from the files. But if I wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
My Code follows.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class GUIstoringObjects extends JFrame implements ActionListener{
private JFrame frame;
private JButton button1, button2, button3, button4, button5, button6;
private JTextField box1, box2, box3;
private JLabel label1, label2, label3;
private JTable table;
private ArrayList<Person> pList = new ArrayList<Person>();
private ArrayList<Object[]> list;
private File f1, f2;
private PrintWriter pWriter;
private Scanner pReader;
public static void main(String[] args) throws FileNotFoundException{
// TODO Auto-generated method stub
GUIstoringObjects gui = new GUIstoringObjects();
gui.frame.setVisible(true);
}
public GUIstoringObjects()
{
initialize();
}
public void initialize()
{
frame = new JFrame("Adding and Saving Person Objects");
frame.setBounds(75,75,813,408);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
label1 = new JLabel("First Name:");
label1.setBounds(32,27,60,25);
frame.getContentPane().add(label1);
label2 = new JLabel("Last Name:");
label2.setBounds(264,27,82,25);
frame.getContentPane().add(label2);
label3 = new JLabel("Phone Number:");
label3.setBounds(504,27,89,25);
frame.getContentPane().add(label3);
box1 = new JTextField();
box1.setBounds(102,26,140,27);
frame.getContentPane().add(box1);
box2 = new JTextField();
box2.setBounds(354,26,140,27);
frame.getContentPane().add(box2);
box3 = new JTextField();
box3.setBounds(599,26,140,27);
frame.getContentPane().add(box3);
button1 = new JButton("Add Person");
button1.addActionListener(this);
button1.setBounds(120,76,122,33);
frame.getContentPane().add(button1);
button2 = new JButton("Remove Person");
button2.addActionListener(this);
button2.setBounds(120,121,122,33);
frame.getContentPane().add(button2);
button3 = new JButton("Display Person List");
button3.addActionListener(this);
button3.setBounds(252,76,154,33);
frame.getContentPane().add(button3);
button4 = new JButton("Save Person List");
button4.addActionListener(this);
button4.setBounds(416,76,154,33);
frame.getContentPane().add(button4);
button5 = new JButton("Load Person List");
button5.addActionListener(this);
button5.setBounds(416,121,154,33);
frame.getContentPane().add(button5);
button6 = new JButton("Quit Program");
button6.addActionListener(this);
button6.setBounds(599,76,140,33);
frame.getContentPane().add(button6);
table = new JTable();
table.setBounds(0,176,797,194);
frame.getContentPane().add(table);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = (((JButton) e.getSource()).getActionCommand());
if(action.equals("Add Person"))
{
String fName = box1.getText();
String lName = box2.getText();
String pNo = box3.getText();
Person p = new Person(fName,lName,pNo);
pList.add(p);
JOptionPane.showMessageDialog(null, fName+" has been Added!");
box1.setText("");
box2.setText("");
box3.setText("");
}
if(action.equals("Remove Person"))
{
String nameChecker = box1.getText();
for(int i = 0; i<pList.size(); i++)
{
if(nameChecker.equals(pList.get(i).getFName()))
{
pList.remove(i);
JOptionPane.showMessageDialog(null, nameChecker+" has been deleted!");
}
}
}
if(action.equals("Display Person List"))
{
list = new ArrayList<Object[]>();
for (int i = 0; i < pList.size(); i++) {
list.add(new Object[] {
pList.get(i).getFName(),
pList.get(i).getLName(),
pList.get(i).getPNo()
});
}
table.setModel(new DefaultTableModel(list.toArray(new Object[][] {}),
new String[] {"First Name", "Surname", "Phone Number"}));
}
if(action.equals("Save Person List"))
{
f1 = new File("PersonList.txt");
try {
pWriter = new PrintWriter(f1);
for(Person p: pList)
{
pWriter.println(p.getFName());
pWriter.println(p.getLName());
pWriter.println(p.getPNo());
}
JOptionPane.showMessageDialog(null, "Person List Stored in File 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Load Person List"))
{
f2 = new File("PersonList.txt");
try {
pReader = new Scanner(f2);
while (pReader.hasNext())
{
String fName = pReader.nextLine();
String lName = pReader.nextLine();
String pNo = pReader.nextLine();
Person p = new Person(fName,lName,pNo);
pList.add(p);
}
JOptionPane.showMessageDialog(null, "Person List Loaded from 'PersonList.txt'");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(action.equals("Quit Program"))
{
System.exit(0);
}
}
}
And This is my person object below
public class Person {
private String fName, lName, pNo;
public Person(String fName, String lName, String pNo)
{
setFName(fName);
setLName(lName);
setPNo(pNo);
}
public void setFName(String fName)
{
this.fName = fName;
}
public void setLName(String lName)
{
this.lName = lName;
}
public void setPNo(String pNo)
{
this.pNo = pNo;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public String getPNo()
{
return pNo;
}
public String toString()
{
return getFName()+" "+getLName()+" "+getPNo();
}
public void print()
{
System.out.println(toString());
}
}
As I already said above, for argument sake we had
Bill
Gates
088491038
Cristiano
Ronaldo
0048103874
The Code would be able to read from the file, but once I tried to add more people from the arraylist, it just wouldn't work, can someone help me out?
But if i wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.
Whenever you create an object of PrintWriter, it clear the data of the existing file.
pWriter = new PrintWriter(f1);
You should use append mode property of FileWriter to append the data in the existing file.
FileWriter fileWriter = new FileWriter(f1, true);
^--------- Append Mode
pWriter = new PrintWriter(fileWriter, true);
^----------- Auto Flush
You should close to stream after finishing all the read/writer operation. Better use auto flush property of PrintWriter to avoid manually calling flush() method.
Handle the resources carefully using Java 7- The try-with-resources Statement or finally block.
I made an application, which got quite alot textfields, which clear text on focus. When i run the application, the application works abolutely fine. Then, i made a menu, which give me a choice to open the application, or open the txt my FileWriter wrote. Now, when i run application using menu, it focuses on the first textfield. How do i make the menu run the application without focus on first textfield?? as i said, when i run application without menu, it doesnt focus.. hope u can help!
Best Regards, Oliver.
Menu:
public class menu extends JFrame{
private JFrame fr;
private JButton b1;
private JButton b2;
private JPanel pa;
public static void main(String[] args){
new menu();
}
public menu(){
gui();
}
public void gui(){
fr = new JFrame("menu");
fr.setVisible(true);
fr.setSize(200,63);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLocationRelativeTo(null);
pa = new JPanel(new GridLayout(1,2));
b1 = new JButton("Infostore");
b2 = new JButton("log");
pa.add(b1);
pa.add(b2);
fr.add(pa);
Eventhandler eh = new Eventhandler();
b1.addActionListener(eh);
b2.addActionListener(eh);
}
private class Eventhandler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==b1){
IS is = new IS();
fr.setVisible(false);
}
if(event.getSource()==b2){
try{
Runtime.getRuntime().exec("C:\\Windows\\System32\\notepad C:\\Applications\\Infostore.txt");
}catch(IOException ex){
ex.printStackTrace();
}
System.exit(1);
}
}
}
}
Application:
public class IS extends JFrame{
private JLabel fname;
private JTextField name;
private JTextField lname;
private JLabel birth;
private JTextField date;
private JTextField month;
private JTextField year;
private JTextField age;
private JButton cont;
private JLabel lcon;
private JTextField email;
private JTextField numb;
String inumb;
int[] check = {0,0,0,0,0,0,0};
int sum=0;
private JPanel p;
private JFrame f;
public static void main(String[] args){
new IS();
}
public IS(){
gui();
}
public void gui(){
f = new JFrame("Infostore");
f.setVisible(true);
f.setSize(200,340);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
p = new JPanel();
fname = new JLabel("Name ");
name = new JTextField("Name",12);
lname = new JTextField("Last name",12);
birth = new JLabel("Birthday");
date = new JTextField("Date",12);
month = new JTextField("Month",12);
year = new JTextField("Year",12);
age = new JTextField("Your age",12);
lcon = new JLabel("Contact");
email = new JTextField("E-mail",12);
numb = new JTextField("Phone (optional)",12);
cont = new JButton("Store Information");
p.add(fname);
p.add(name);
p.add(lname);
p.add(birth);
p.add(date);
p.add(month);
p.add(year);
p.add(age);
p.add(lcon);
p.add(email);
p.add(numb);
p.add(cont);
f.add(p);
f.setVisible(true);
name.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jname = name.getText();
if(jname.equalsIgnoreCase("name")){
name.setText("");
}
}
public void focusLost(FocusEvent e) {
String jname = name.getText();
if(jname.equals("")){
name.setText("Name");
check[0] = 0;
}else{
check[0] = 1;
}
}});
lname.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jlname = lname.getText();
if(jlname.equalsIgnoreCase("last name")){
lname.setText("");
}
}
public void focusLost(FocusEvent e) {
String jlname = lname.getText();
if(jlname.equals("")){
lname.setText("Last name");
check[1] = 0;
}else{
check[1] = 1;
}
}});
date.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jdate = date.getText();
if(jdate.equalsIgnoreCase("date")){
date.setText("");
}
}
public void focusLost(FocusEvent e) {
String jdate = date.getText();
if(jdate.equals("")){
date.setText("Date");
check[2] = 0;
}else{
check[2] = 1;
}
}});
month.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jmonth = month.getText();
if(jmonth.equalsIgnoreCase("month")){
month.setText("");
}
}
public void focusLost(FocusEvent e) {
String jmonth = month.getText();
if(jmonth.equals("")){
month.setText("Month");
check[3] = 0;
}else{
check[3]=1;
}
}});
year.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jyear = year.getText();
if(jyear.equalsIgnoreCase("year")){
year.setText("");
}
}
public void focusLost(FocusEvent e) {
String jyear = year.getText();
if(jyear.equals("")){
year.setText("Year");
check[4] = 0;
}else{
check[4] = 1;
}
}});
age.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jage = age.getText();
if(jage.equalsIgnoreCase("your age")){
age.setText("");
}
}
public void focusLost(FocusEvent e) {
String jage = age.getText();
if(jage.equals("")){
age.setText("Your age");
check[5] = 0;
}else{
check[5] = 1;
}
}});
email.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jemail = email.getText();
if(jemail.equalsIgnoreCase("e-mail")){
email.setText("");
}
}
public void focusLost(FocusEvent e) {
String jemail = email.getText();
if(jemail.equals("")){
email.setText("E-mail");
check[6]=0;
}else{
check[6]=1;
}
}});
numb.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
String jnumb = numb.getText();
if(jnumb.equalsIgnoreCase("phone (optional)")){
numb.setText("");
}
}
public void focusLost(FocusEvent e) {
String jnumb = numb.getText();
if(jnumb.equals("")){
numb.setText("Phone (optional)");
}else{
}
}
});
eventh eh = new eventh();
cont.addActionListener(eh);
}
private class eventh implements ActionListener{
public void actionPerformed(ActionEvent event){
sum = check[0] + check[1] + check[2] + check[3] + check[4] + check[5] + check[6];
if(event.getSource()==cont&&sum==7){
String sname = name.getText();
String slname = lname.getText();
String sdate = date.getText();
String smonth = month.getText();
String syear = year.getText();
String sage = age.getText();
String semail = email.getText();
String snumb = numb.getText();
if(snumb.equalsIgnoreCase("Phone (optional)")){
numb.setText("");
}
String inumb = ("Phone: "+numb.getText());
String info = ("Name: "+sname+" "+slname+" "+"Birthday: "+sdate+"-"+smonth+"-"+syear+" "+" Age:"+sage+" "+"E-mail:"+" "+ semail+" "+inumb);
JOptionPane.showMessageDialog(null,info);
filewriter fw = new filewriter();
fw.setName(info);
fw.writeFile();
try{
Thread.sleep(150);
}catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
System.exit(0);
}else{
JOptionPane.showMessageDialog(null,"Please fill out all fields");
}
}
}
}
You must force all the parents of the textfield to get focus, then we can set focus on the textfield
Java Textfield focus
import org.jsoup.Jsoup;
#SuppressWarnings("unused")
public class SimpleWebCrawler extends JFrame implements ActionListener {
JTextField yourInputField = new JTextField(20);
static JTextArea _resultArea = new JTextArea(200, 200);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
private final static String newline = "\n";
JButton jButton = new JButton("Send Text");
public SimpleWebCrawler() throws MalformedURLException {
yourInputField.addActionListener(new ActionListener());
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
JTextField textfield = (JTextField)evt.getSource();
process(textfield.getText());
}
}
String word2 = yourInputField.getText();
_resultArea.setEditable(false);
try {
URL my_url = new URL("http://" + word2 + "/");
BufferedReader br = new BufferedReader(new InputStreamReader(
my_url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
_resultArea.append(strTemp + newline);
}
} catch (Exception ex) {
ex.printStackTrace();
}
_resultArea.append("\n");
_resultArea.append("\n");
_resultArea.append("\n");
String url = "http://" + word2 + "/";
print("Fetching %s...", url);
try{
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
System.out.println("\n");
BufferedWriter bw = new BufferedWriter(new
FileWriter("C:\\Users\\user\\fypworkspace\\FYP\\Link\\abc.txt"));
_resultArea.append("\n");
for (Element link : links) {
print(" %s ", link.attr("abs:href"), trim(link.text(), 35));
bw.write(link.attr("abs:href"));
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();
} catch (IOException e1) {
}
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
content.add(yourInputField,BorderLayout.SOUTH);
content.add(jButton, BorderLayout.EAST);
this.setContentPane(content);
this.setTitle("Crawled Links");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
}
private static void print(String msg, Object... args) {
_resultArea.append(String.format(msg, args) +newline);
}
private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width - 1) + ".";
else
return s;
}
//.. Get the content pane, set layout, add to center
public static void main(String[] args) throws IOException {
JFrame win = new SimpleWebCrawler();
win.setVisible(true);
}
}
I got this error cannot instantiate type actionlistener. The line of code is :
yourInputField.addActionListener(new ActionListener());
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
JTextField textfield = (JTextField)evt.getSource();
process(textfield.getText());
}
}
I am trying to create a JTextField to receive input from the user. Still unsuccessful. WHat has caused the error ?
If your trying to use an anonymous inner class, it should look like that:
yourInputField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JTextField textfield = (JTextField)evt.getSource();
process(textfield.getText());
}
});
But if you want to use a nested class it can look like this:
yourInputField.addActionListener(new MyActionListener());
and then somewhere out of the method you declare the nested class:
private class MyActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
TextField textfield = (JTextField)evt.getSource();
process(textfield.getText());
}
}
ActionListener is an interface not a class, and you can not instantiate interfaces.
Replace:
yourInputField.addActionListener(new ActionListener());
with:
yourInputField.addActionListener(new MyActionListener());
ActionListener is an interface and you cannot instantiate an interface like new ActionListener();
I think in your case you want
yourInputField.addActionListener(new MyActionListener());
Firstly you need to import ActionListener and ActionEvent, by putting the following lines at the top of your class:
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
Next, move your MyActionListener inner class somewhere other than your constructor - a good place would be after your main method, at the bottom of the class (not inside the main method though).
Finally, replace 'new ActionListener()' with 'new MyActionListener()' in the following line:
yourInputField.addActionListener(new ActionListener());
It will become:
yourInputField.addActionListener(new MyActionListener());