I am still pretty new to Java and for my class, we have to make a web browser without JEditor. I just need to figure out how to use the socket when a user types in the JTextField and then make it go to that website. Also, I am only supposed to use http:// not https:// if that makes a difference. Anything helps! Thanks!
import javax.swing.*;
import java.awt.*;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.Socket;
import java.io.*;
public class WebPanel extends JPanel{
PrintWriter pw;
JTextField text = new JTextField("http://www.");
public WebPanel(){
//trying to connect to the website
try {
Socket s = new Socket(text, 80); //<<<---where the error is thrown
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os, true);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
//set layout
setLayout(null);
ButtonHandler bh = new ButtonHandler();
text.addActionListener(bh);
text.setBounds(185, 10, 315, 25);
add(text);
//buttons
JButton goButton = new JButton("GO");
goButton.addActionListener(bh);
add(goButton);
goButton.setBounds(500, 10, 75, 25);
JButton backButton = new JButton("BACK");
backButton.addActionListener(bh);
add(backButton);
backButton.setBounds(2, 10, 75, 25);
JButton forwardButton = new JButton("FORWARD");
forwardButton.addActionListener(bh);
add(forwardButton);
forwardButton.setBounds(80, 10, 100, 25);
}
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//buttons for later
if(e.getActionCommand().equals("GO")){
String input = text.getText();
System.out.println("You searched for: " + input);
pw.flush();
}else if(e.getActionCommand().equals("BACK")){
System.out.println("you pressed the back button");
pw.flush();
} else if(e.getActionCommand().equals("FORWARD")){
System.out.println("You pressed the forward button");
pw.flush();
}
}
}
}
}
For simple cases you don't need to use Sockets. You can use URL class like this:
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class URLReadTest {
public static void main(String[] args) throws Exception {
InputStream is = new URL("http://stackoverflow.com/").openStream();
String html = IOUtils.toString(is);
is.close();
System.out.println(html); // Parse HTML here
}
}
And then you have to parse returned HTML by yourself before you can visualize it of course.
Related
This question already has answers here:
Loading a text file into a textarea
(4 answers)
Trying to read a text file into a JTextArea
(2 answers)
Open a text file in the default text editor... via Java?
(3 answers)
Closed 2 months ago.
I am currently making a java project that simulates a website for swimmers. It has multiple classes and incorporates the Jswing GUI. I have buttons that are used to display other classes GUI and data, but I was wondering if there was a way to have it so when I click a button, it would pull up a .txt file as a pop up externally, as opposed to just reading and writing the .txt files data into my console.
I had initially tried to display information from a .txt file into a JLabel or JTextField so it could be seen but I had abandoned that idea in order to pursue the easier and simplier idea of bringing up a entirely new window of a .txt file
package finalProject;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class FrontInterface extends JPanel {
private static JButton nSwimmer;
private static JButton cSwimmer;
private static JButton coach;
private JLabel heading;
private static JButton equipment;
public FrontInterface() {
//construct components
nSwimmer = new JButton ("New Swimmer");
cSwimmer = new JButton ("Current Swimmer");
coach = new JButton ("Coach");
heading = new JLabel ("Welcome to the Swimming Station");
equipment = new JButton ("Equipment");
//adjust size and set layout
setPreferredSize (new Dimension (752, 425));
setLayout (null);
//add components
add (nSwimmer);
add (cSwimmer);
add (coach);
add (heading);
add (equipment);
//set component bounds (only needed by Absolute Positioning)
nSwimmer.setBounds (280, 150, 200, 20);
cSwimmer.setBounds (280, 175, 200, 20);
coach.setBounds (280, 200, 200, 20);
heading.setBounds (280, 95, 195, 30);
equipment.setBounds (280, 225, 200, 25);
}
public static void showWindow(){
JFrame frame = new JFrame ("Front Interface");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FrontInterface());
frame.pack();
frame.setVisible(true);
nSwimmer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
NewSwimmerForm w2 = new NewSwimmerForm();
w2.showWindow();
}
});
cSwimmer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
CurrentSwimmer w2_1 = new CurrentSwimmer();
w2_1.showWindow();
}
});
coach.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
NewSwimmerForm w2 = new NewSwimmerForm();
w2.showWindow();
}
});
equipment.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
NewSwimmerForm w2 = new NewSwimmerForm();
w2.showWindow();
}
});
frame.setVisible(true);
}
public static void main (String[] args) {
showWindow();
}
}
And below is the code that the cSwimmer button will take you to upon clicking the cSwimmer button:
package finalProject;
import finalProject.FrontInterface;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class CurrentSwimmer extends JPanel {
private static JTextArea informationHeader;
public static void showWindow(){
try{
File file = new File("C:\\Users\\trent\\Desktop\\Intro to Computer Science\\Eclipse Codes\\FinalProject\\src\\finalProject\\history.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String [] args) {
showWindow();
}
}
Now, I am completely unsure of how to go about my situation, whether it be I display the information from the .txt file onto a jTextArea or if I should just create a method to make a .txt file open externally and replace the pop up window I would otherwise have with the writing to JTextArea.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {
JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});
So, in this function, I want to read some text files within a mentioned directory/folder by input. User selects the directories/folder using JFILECHOOSER method and the output will be listed in a textbox [Directory]. Lets say that fileName is the text field where users input the name of the file, after users input their file name, they click on a start button. The start button functions on whereby it will look into the given directory/folder [the textbox] and search for text files and output the text files' name using system.out.printIn. I have not tried the code for directory/folder path because I'm not sure how to code for it. Any help or guide to this problem? I have only created one class and I'm new to JAVA GUI
The full code is as below:
package com.directory.file;
import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.TextArea;
import java.awt.TextComponent;
import java.awt.Event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
import javax.lang.model.element.VariableElement;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Component;
import java.sql.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JSplitPane;
import javax.swing.JLayeredPane;
import javax.swing.JDesktopPane;
import javax.swing.JComboBox;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SpinnerDateModel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.text.JTextComponent;
import java.awt.Color;
import javax.swing.SwingConstants;
import java.awt.ComponentOrientation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import com.toedter.calendar.JDateChooser;
import javax.swing.JSpinner;
import org.eclipse.wb.swing.FocusTraversalOnArray;
public class Directory extends JFrame {
private JPanel contentPane;
private JTextField txtKeyword;
private JTextField fileName;
private JTextArea jTextArea1;
private JDateChooser dateChooser;
private JSpinner spinner_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Directory frame = new Directory();
frame.setVisible(true);
frame.setSize(450,630);
frame.fileName.requestFocus();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Directory() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 436, 631);
contentPane = new JPanel();
contentPane.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDirectory = new JLabel("Directory:");
lblDirectory.setBounds(20, 29, 55, 24);
contentPane.add(lblDirectory);
JLabel lblDate = new JLabel("Date:");
lblDate.setBounds(37, 141, 55, 24);
contentPane.add(lblDate);
txtKeyword = new JTextField();
txtKeyword.setHorizontalAlignment(SwingConstants.CENTER);
txtKeyword.setToolTipText("");
txtKeyword.setColumns(10);
txtKeyword.setBounds(85, 193, 229, 20);
contentPane.add(txtKeyword);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setDateFormatString("YYYMMd");
dateChooser.setBounds(85, 141, 229, 20);
contentPane.add(dateChooser);
JLabel lblKeyword = new JLabel("Keyword:");
lblKeyword.setBounds(20, 191, 55, 24);
contentPane.add(lblKeyword);
JSeparator separator = new JSeparator();
separator.setBounds(148, 204, -113, 34);
contentPane.add(separator);
JButton btnExport = new JButton("Export");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnExport.setBounds(324, 556, 89, 23);
contentPane.add(btnExport);
final JLabel Directory = new JLabel("");
Directory.setBorder(new LineBorder(new Color(0, 0, 0)));
Directory.setBounds(85, 30, 290, 22);
contentPane.add(Directory);
int min = 0;
int max = 23;
int step = 1;
int initValue = 0;
SpinnerModel sm = new SpinnerNumberModel(initValue, min, max, step);
final JSpinner spinner_1 = new JSpinner(new SpinnerNumberModel(0, 0, 23-1, 1));
spinner_1.setBounds(324, 143, 89, 20);
contentPane.add(spinner_1);
JButton btnNewButton = new JButton("...");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename =f.getAbsolutePath();
Directory.setText(filename);
});
btnNewButton.setBounds(377, 30, 36, 23);
contentPane.add(btnNewButton);
final JTextArea jTextArea1 = new JTextArea();
jTextArea1.setRows(15);
jTextArea1.setColumns(15);
jTextArea1.setBounds(42, 249, 351, 294);
jTextArea1.setLineWrap(true);
jTextArea1.setWrapStyleWord(true);
contentPane.add(jTextArea1);
jTextArea1.setEditable(false);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {
JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});
btnStart.setBounds(324, 215, 89, 23);
contentPane.add(btnStart);
JLabel lblFileName_1 = new JLabel("File Name:");
lblFileName_1.setBounds(20, 79, 75, 24);
contentPane.add(lblFileName_1);
fileName = new JTextField();
fileName.setToolTipText("");
fileName.setHorizontalAlignment(SwingConstants.CENTER);
fileName.setColumns(10);
fileName.setBounds(85, 81, 290, 20);
contentPane.add(fileName);
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{fileName, lblDirectory, lblDate, txtKeyword, btnStart, lblKeyword, separator, btnExport, Directory, dateChooser, dateChooser.getCalendarButton(), spinner_1, btnNewButton, jTextArea1, lblFileName_1}));
}
}
Problem #1
You only ever use the fileName value when trying to open the file...
FileReader fr = new FileReader(filename);
A file is a catenation of the directory and the name, for example...
FileReader fr = new FileReader(new File(Directory.getText(), filename));
Problem #2
You're doing some kind of pre-emptive read on the file which is not required...
if (filename != null){
String text = txtKeyword.getText();
String line;
boolean hasError = true;
while ((line = br.readLine()) != null) {
You should just start reading the file, otherwise you've lost the first line of text
Problem #3
You're not closing the streams in the event of some kind of exception...
try {
FileReader fr = new FileReader(new File(Directory.getText(), filename));
BufferedReader br = new BufferedReader(fr);
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
}
If, for some reason, an exception occurs while you are opening or reading the streams, they can never be closed...at least not until the JVM closes
Instead, you should either be using try-with-resources if you're using Java 7+ or a finally block to ensure the streams are closed, for example...
BufferedReader br = null;
try {
String filename = fileName.getText();
br = new BufferedReader(new FileReader(new File(Directory.getText(), filename)));
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
try {
br.close();
} catch (Exception e) {
}
}
It would also be of more help to you if you at least dumped the stack trace of the actual exception or logged it some how...
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
Problem #4
null layout. Pixel perfect layouts are an illusion in modern UI design, you have no control over fonts, DPI, rendering pipelines or other factors that will change the way that you components will be rendered on the screen.
Swing was designed to work with layout managers to overcome these issues. If you insist on ignoring these features and work against the API design, be prepared for a lot of headaches and never ending hard work...
I have some problems with my code and i would need some help if you can please(and explain it a bit so i can understand in the future:)), so this is my code and what i need is that my JButton to action a shutdown command and the shutdown command to be delayed from the seconds i input in my JTextfield.
So my code so far is :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Shutdown extends JFrame{
InputStream text1;
JButton start;
String shutdownCmd;
public Shutdown() {
this.setTitle("Shutdown When you want");
setSize(300, 150);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel desc1 = new JLabel("Time until shutdown : ");
desc1.setBounds(95, 25, 125, 25);
add(desc1);
JTextField text1 = new JTextField();
text1.setBounds(95, 45, 120, 25);
text1.setForeground(Color.BLACK);
text1.setToolTipText("Introdu textu aici");
add(text1);
JButton start = new JButton("Start Shudown");
start.setBounds(95, 75, 120, 25);
add(start);
ActionListener eventstart = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){
try {
ShutdownCmd();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
start.addActionListener(eventstart);
}
public void ShutdownCmd() throws IOException{
Runtime runtime = Runtime.getRuntime();
BufferedReader br=new BufferedReader(new InputStreamReader(text1));
long a=Long.parseLong(br.readLine());
Process proc = runtime.exec("shutdown -s -t "+a);
System.exit(0);
}
}
Thank you or the help in advanced !!! :D
Lots of things jump out at me here, but...
Redeclare text1 as JTextField instead of an InputStream...
//InputStream text1;
private JTextField text1;
This will allow you to access the field and it's value from anywhere in the class.
Make sure you aren't shadowing the variables when you create the text field...
//JTextField text1 = new JTextField();
text1 = new JTextField(10);
Make use of ProcessBuilder instead of Runtime.getRuntime(). It will make your life easier to deals with parameters much better
ProcessBuilder pb = new ProcessBuilder("shutdown", "-s", "-t", text1.getText());
pb.redirectError();
Process p = pb.start();
The action command will always be null as you never set, so the following will cause you a NullPointerException
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){
When you create your button, you need to set the action command...
JButton start = new JButton("Start Shudown");
start.setActionCommand("Start Shudown");
Additional suggestions...
Make use of appropriate layout managers. Even across the same OS, it's possible your application will need to deal with different screen resolutions, DPI, fonts etc...
Avoid extending directly from top level containers like JFrame. Instead, base you application on something like JPanel. It makes your application for flexible and re-usable.
All you need to do is make the JTextField a field:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Shutdown extends JFrame{
JTextField text1;
JButton start;
String shutdownCmd;
public Shutdown() {
this.setTitle("Shutdown When you want");
setSize(300, 150);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel desc1 = new JLabel("Time until shutdown : ");
desc1.setBounds(95, 25, 125, 25);
add(desc1);
text1 = new JTextField();
text1.setBounds(95, 45, 120, 25);
text1.setForeground(Color.BLACK);
text1.setToolTipText("Introdu textu aici");
add(text1);
JButton start = new JButton("Start Shudown");
start.setBounds(95, 75, 120, 25);
add(start);
ActionListener eventstart = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionstart = arg0.getActionCommand();
if(actionstart.equals("Start Shudown")){
try {
ShutdownCmd();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
start.addActionListener(eventstart);
}
public void ShutdownCmd() throws IOException{
Runtime runtime = Runtime.getRuntime();
long a=Long.parseLong(text1.getText());
Process proc = runtime.exec("shutdown -s -t "+a);
System.exit(0);
}
}
If it's global, you can use it in any of this object's functions, so you can get the Text from the textField from anywhere you want inside your JFrame Object.
I hope this is what you want to do. If its not explained well enough, please tell me. ;)
This is my code and below the code is the problem i have :
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
public class Write extends JFrame {
JTextArea text;
public Write(){
this.setTitle("Lista Carti!");
setSize(400, 200);
setResizable(false);
setLocation(370, 150);
setLayout(null);
JLabel lbltitlu = new JLabel("Titlu");
lbltitlu.setBounds(85, 5, 120, 25);
this.add(lbltitlu);
JTextArea text = new JTextArea();
text.setSize(199,199);
text.setBounds(85, 65, 120, 25);
add(text);
JButton btn = new JButton("Adauga text");
btn.setSize(99,99);
btn.setBounds(125, 125, 120, 25);
add(btn);
ActionListener listenerbtn = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO auto- generated method
String actionbtn = arg0.getActionCommand();
if (actionbtn.equals("Adauga")) {
Adauga();
}
}
};
btn.addActionListener(listenerbtn);
}
public void Adauga(){
String filename = "test.txt";
FileWriter writer = null;
try {
writer = new FileWriter(filename);
text.write(writer);
} catch (IOException exception) {
System.err.println("Save oops");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
}
This is my code to write into a file,but it does autowrite when i hover the button and when i reenter the application it won't write again in the same file, any help please? ----- Old request
New request - >
I have edited my code,implemented actionListener but it dosen't input anything to the external file as it should. Can please some one tell me why or where did i done my mistake,i'm a noob programmer by the way? :D
Thank you!
To append to the file , use the constructor File(filename,append).
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
FileWriter fw = new FileWriter(filename,true);
I am currently working on an applet and am having a bit of trouble finishing it off. My code works just fine however I need to change the final portion from a JOptionDialog Message Dialog into just a JLabel that gets added to the applet. I've tried every way I can think of and am still coming up short. My current code looks as followed:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
JOptionPane.showMessageDialog(null, "Access Granted");
return
}
else {
JOptionPane.showMessageDialog(null, "Access Denied");
}
}
}
}
Please help!
Try this one:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
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.JOptionPane;
import javax.swing.JTextField;
public class Password extends JApplet implements ActionListener {
Container PW = getContentPane();
JLabel password = new JLabel("Enter Password(and click OK):");
JLabel message = new JLabel();
Font font1 = new Font("Times New Roman", Font.BOLD, 18);
JTextField input = new JTextField(7);
JButton enter = new JButton("OK");
public void start() {
PW.add(password);
password.setFont(font1);
PW.add(input);
PW.add(enter);
PW.add(message);
PW.setLayout(new FlowLayout());
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String pass1 = input.getText();
String passwords[] = {"Rosebud", "Redrum", "Jason", "Surrender", "Dorothy"};
for(int i=0;i<passwords.length;i++) {
if (pass1.equalsIgnoreCase(passwords[i])) {
message.setText("Access Granted");
return;
}
else {
message.setText("Access Denied");
}
}
}
}
Its sample code so no alignment is done it will show message next to button. You can change alignment as you wish ;)