I am creating a web browser in java and am receiving the following error when I attempt to run it:
Exception in thread "main" java.net.MalformedURLException: no protocol:
I have not been able to find an answer to my particular problem but I believe it has something to do with my socket. Do I simply need to add a MalformedURLException? Any help is appreciated.
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Browser extends JFrame {
public JPanel addressPanel, windowPanel;
public JLabel addressLabel;
public JTextField textField;
public JEditorPane windowPane;
public JScrollPane windowScroll;
public JButton addressButton;
private Search search = new Search();
public Browser() throws IOException {
addressLabel = new JLabel(" address: ", SwingConstants.CENTER);
textField = new JTextField("Enter a web address..");
textField.addActionListener(search);
addressButton = new JButton("Go");
addressButton.addActionListener(search);
windowPane = new JEditorPane("");
windowPane.setContentType("text/html");
windowPane.setEditable(false);
addressPanel = new JPanel(new BorderLayout());
windowPanel = new JPanel(new BorderLayout());
addressPanel.add(addressLabel, BorderLayout.WEST);
addressPanel.add(textField, BorderLayout.CENTER);
addressPanel.add(addressButton, BorderLayout.EAST);
windowScroll = new JScrollPane(windowPane);
windowPanel.add(windowScroll);
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(addressPanel, BorderLayout.NORTH);
pane.add(windowPanel, BorderLayout.CENTER);
setTitle("Web Browser");
setSize(1000, 1000);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class Search implements ActionListener {
public void actionPerformed(ActionEvent ea) {
String line;
try {
Socket socket = new Socket(textField.getText(), 80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.print("GET / HTTP/1.1\r\n");
out.print(textField.getText() + "\r\n\r\n");
out.flush();
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
Browser browser = new Browser();
}
}
The problem was because the line bellow:
windowPane = new JEditorPane("");
Just change to
windowPane = new JEditorPane();
According to JEditorPane constructor javadoc:
Creates a JEditorPane based on a string containing a URL specification.
#param url the URL
#exception IOException if the URL is null or cannot be accessed
Related
at the moment I am creating a simple chat program that will allow you to communicate between a server. I am having an issue accessing the username variable when it is used in one file in another file. The user will enter his name, this is done in the ChatGUI file, then when he enters the chat room a EchoFrame is created, which is in the EchoFrame file. Also in the EchoFrame file, I want to append the username to the users message, and also announce when they connect to the chatroom and when they leave the chat room. I hope I was clear on explaining my issue, any other information needed please let me know!
EchoFrame
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class EchoFrame extends Frame{
EchoPanel ep;
Button sendMessage;
public EchoFrame(){
setSize(500,500);
setTitle("Echo Client");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
ep = new EchoPanel();
add(ep, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args){
EchoFrame ef = new EchoFrame();
}
}
class EchoPanel extends Panel implements ActionListener, Runnable{
TextField tf;
TextArea ta;
Button connect, disconnect;
Socket s;
BufferedReader br;
PrintWriter pw;
Thread t;
String fromServer;
String username;
public EchoPanel(){
setLayout(new BorderLayout());
tf = new TextField();
tf.setEditable(false);
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
ta = new TextArea();
ta.setEditable(false);
add(ta, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
connect = new Button("Connect");
connect.addActionListener(this);
buttonPanel.add(connect);
disconnect = new Button("Disconnect");
disconnect.setEnabled(false);
disconnect.addActionListener(this);
buttonPanel.add(disconnect);
add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == connect){
try{
s = new Socket("127.0.0.1", 8189);
ta.append(username + " has entered the chat room. \n");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
}catch(UnknownHostException uhe){
System.out.println(uhe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
t = new Thread(this);
t.start();
tf.setEditable(true);
connect.setEnabled(false);
disconnect.setEnabled(true);
}else if(ae.getSource() == disconnect){
try{
pw.close();
br.close();
s.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
t = null;
ta.append(username + " has disconnected from chat room. \n");
tf.setEditable(false);
connect.setEnabled(true);
disconnect.setEnabled(false);
}else if(ae.getSource() == tf){
String fromTf = tf.getText();
pw.println(fromTf);
tf.setText("");
}else{
//additional events
}
}
public void run (){
fromServer = "";
try{
while((fromServer = br.readLine()) != null){
ta.append(username + ":" + fromServer + "\n");
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
ChatGUI
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ChatGUI extends JFrame {
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
JTextField usernameField;
String username;
public ChatGUI() {
setTitle("Chat Program");
setSize(500, 120);
cardPanel = new JPanel();
cl = new CardLayout();
cardPanel.setLayout(cl);
JPanel chooseUsername = new JPanel();
JLabel usernameLabel = new JLabel("Please enter your username:");
chooseUsername.add(usernameLabel);
cardPanel.add(chooseUsername, "Log in");
usernameField = new JTextField(15);
usernameField.setEditable(true);
add(usernameField, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
JButton logInBtn = new JButton("Enter Chat Room");
buttonPanel.add(logInBtn);
logInBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
currentCard = 2;
cl.show(cardPanel, "" + (currentCard));
username = usernameField.getText(); //gets username
EchoFrame ef = new EchoFrame(); //creates message room
}
});
getContentPane().add(cardPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
ChatGUI cl = new ChatGUI();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}
Chat Server
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer{
Socket s;
ArrayList <ChatHandler>handlers;
public ChatServer(){
try{
ServerSocket ss = new ServerSocket(8189);
handlers = new ArrayList<ChatHandler>();
for(;;){
s = ss.accept();
new ChatHandler(s, handlers).start();
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args){
ChatServer tes = new ChatServer();
}
}
Chat Handler
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatHandler extends Thread{
Socket s;
BufferedReader br;
PrintWriter pw;
String temp;
ArrayList <ChatHandler>handlers;
public ChatHandler(Socket s, ArrayList <ChatHandler>handlers){
this.s = s;
this.handlers = handlers;
}
public void run(){
try{
handlers.add(this);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
temp = "";
while((temp = br.readLine()) != null){
for (ChatHandler ch : handlers){
ch.pw.println(temp);
}
System.out.println(temp);
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}finally{
handlers.remove(this);
}
}
}
Make userName static and access it via ChatUI.userName. In actuality, userName shouldn't be in ChatUI. Alternatively, a more heavyweight option would be to get MySQL, set up a database, and connect to it via JDBC, if you're going to have more than one user.
You can also try and follow from these examples: Simple Client And Server Chat Program and Creating a simple Chat Client/Server Solution. They cover key topics, such as multithreading.
I think you should have a server program and a client program, so all variables you need to send to each client can be into the server.
When a client conect to the server a you add that client(username,ipadress,whatever) to a list of connected clients and create a new thread to listen/send to that client. then from the server you can send to all users(threads) the Username and what he wrote if u have a function sendToAll(idThreadSender, threadX.text) or you can sendtothread(threadX,threadY.text) well i think you have a bad structure, thats all.
hope i helped.
I've searched through the forums but keep coming up empty for a solution.
I'm making a sort of library with a GUI program. What I want is for it to save entries via a text file. I can create objects fine with the methods I have, and can save them to a file easily. The problem comes from starting up the program again and populating a Vector with values in the text file. The objects I'm adding have a String value, followed by 7 booleans. When I try to load up from file, the String value is empty ("") and all booleans are false.
How do I get it to read the text before starting the rest of the GUI and filling the Vector right?
EDIT: Sorry for being very vague about it all. I'll post the code, but it's about 337 lines long..
import java.awt.Container;
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.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class SteamLibraryGUI extends JFrame implements ActionListener
{
//For main window
private JButton exitButton, addEntry, editEntry, removeEntry;
private JLabel selectGame, gameCount;
private JComboBox<String> gameCombo;
private Vector<Game> gamesList = new Vector<Game>();
private Vector<String> titleList = new Vector<String>();
private int numGames = gamesList.size();
private int selectedGame;
//For add window
private JFrame addFrame;
private JLabel gameTitle = new JLabel("Title:");
private JTextField titleText = new JTextField(60);
private JCheckBox singleBox, coopBox, multiBox, cloudBox, controllerBox, achieveBox, pcBox;
private JButton addGame, addCancel;
//For edit window
private JFrame editFrame;
private JButton editGame, editCancel;
public SteamLibraryGUI()
{
setTitle("Steam Library Organizer");
addEntry = new JButton("Add a game");
editEntry = new JButton("Edit a game");
removeEntry = new JButton("Remove a game");
exitButton = new JButton("Exit");
selectGame = new JLabel("Select a game:");
gameCount = new JLabel("Number of games:"+numGames);
gameCombo = new JComboBox<String>(titleList);
JPanel selectPanel = new JPanel();
selectPanel.setLayout(new GridLayout(1,2));
selectPanel.add(selectGame);
selectPanel.add(gameCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));
buttonPanel.add(addEntry);
buttonPanel.add(editEntry);
buttonPanel.add(removeEntry);
JPanel exitPanel = new JPanel();
exitPanel.setLayout(new GridLayout(1,2));
exitPanel.add(gameCount);
exitPanel.add(exitButton);
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
pane.add(selectPanel);
pane.add(buttonPanel);
pane.add(exitPanel);
addEntry.addActionListener(this);
editEntry.addActionListener(this);
removeEntry.addActionListener(this);
exitButton.addActionListener(this);
gameCombo.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==addEntry)
addEntry();
if(e.getSource()==editEntry)
editEntry(gamesList.get(selectedGame));
if(e.getSource()==removeEntry)
{
removeEntry(selectedGame);
update();
}
if(e.getSource()==exitButton)
exitProg();
if(e.getSource()==gameCombo)
{
selectedGame = gameCombo.getSelectedIndex();
}
if(e.getSource()==singleBox)
singleBox.isSelected();
if(e.getSource()==coopBox)
coopBox.isSelected();
if(e.getSource()==multiBox)
multiBox.isSelected();
if(e.getSource()==cloudBox)
cloudBox.isSelected();
if(e.getSource()==controllerBox)
controllerBox.isSelected();
if(e.getSource()==achieveBox)
achieveBox.isSelected();
if(e.getSource()==pcBox)
pcBox.isSelected();
if(e.getSource()==addGame)
{
gamesList.add(new Game(titleText.getText(), singleBox.isSelected(), coopBox.isSelected(),
multiBox.isSelected(), cloudBox.isSelected(), controllerBox.isSelected(),
achieveBox.isSelected(), pcBox.isSelected()));
titleList.add(titleText.getText());
addFrame.dispose();
update();
}
if(e.getSource()==addCancel)
addFrame.dispose();
if(e.getSource()==editCancel)
editFrame.dispose();
if(e.getSource()==editGame)
{
gamesList.get(selectedGame).name = titleText.getText();
gamesList.get(selectedGame).single = singleBox.isSelected();
gamesList.get(selectedGame).coop = coopBox.isSelected();
gamesList.get(selectedGame).multi = multiBox.isSelected();
gamesList.get(selectedGame).cloud = cloudBox.isSelected();
gamesList.get(selectedGame).controller = controllerBox.isSelected();
gamesList.get(selectedGame).achieve = achieveBox.isSelected();
gamesList.get(selectedGame).pc = pcBox.isSelected();
titleList.remove(selectedGame);
titleList.add(titleText.getText());
editFrame.dispose();
update();
}
}
public void update()
{
Collections.sort(titleList);
Collections.sort(gamesList);
gameCombo.updateUI();
titleText.setText("");
gameCombo.setSelectedIndex(-1);
numGames = gamesList.size();
gameCount.setText("Number of games:"+numGames);
}
public void addEntry()
{
addFrame = new JFrame("Add Entry");
addFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
addFrame.getContentPane();
addFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(false);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(false);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(false);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(false);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(false);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(false);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(false);
addGame = new JButton("Add game");
addCancel = new JButton("Cancel");
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(addGame);
buttonPanel.add(addCancel);
addFrame.add(titlePanel);
addFrame.add(checkPanel);
addFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
addGame.addActionListener(this);
addCancel.addActionListener(this);
addFrame.pack();
addFrame.setVisible(true);
}
public void editEntry(Game g)
{
editFrame = new JFrame("Edit Entry");
editFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
editFrame.getContentPane();
editFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(g.single);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(g.coop);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(g.multi);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(g.cloud);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(g.controller);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(g.achieve);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(g.pc);
editGame = new JButton("Edit game");
editCancel = new JButton("Cancel");
titleText.setText(g.name);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(editGame);
buttonPanel.add(editCancel);
editFrame.add(titlePanel);
editFrame.add(checkPanel);
editFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
editGame.addActionListener(this);
editCancel.addActionListener(this);
editFrame.pack();
editFrame.setVisible(true);
}
public void removeEntry(int g)
{
Object[] options = {"Yes, remove the game", "No, keep the game"};
int n = JOptionPane.showOptionDialog(null, "Are you sure you want to remove this game from the list?",
"Remove game?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
if (n==0)
{
gamesList.remove(g);
titleList.remove(g);
}
}
public void exitProg()
{
try
{
PrintWriter out = new PrintWriter("games.txt");
out.flush();
for(int i=0;i<gamesList.size();i++)
{
out.print(gamesList.get(i).toString());
}
out.close();
}
catch (FileNotFoundException e) {}
System.exit(0);
}
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scanner in = new Scanner("games.txt");
while(in.hasNextLine())
{
String line = in.nextLine();
String[] options = line.split("|");
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
}
}
There's also a Game class, but it's simply 1 String, and then 7 booleans.
There were two significant bugs in the code. First, Scanner was constructed with a string parameter (which means that the Scanner scanned the string, not the file named by the string). Second, the pipe character "|" is a regular expression metacharacter. That is important because line.split() splits on regular expressions. Thus, the "|" has to be escaped. The main() function works fine if it is written as follows (with debugging output code included to show that each step is working correctly):
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
Scanner in = new Scanner(new File("games.txt"));
while(in.hasNextLine())
{
System.out.println("line = ");
String line = in.nextLine();
System.out.println(line);
String[] options = line.split("\\|");
System.out.println("Options = ");
for (String s : options)
{
System.out.println(s);
}
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
} catch (IOException x)
{
System.err.println(x);
}
}
There is one other important Gotcha: The method exitProg() writes the "games.txt" file out again before the program finishes. This creates a problem if the file was read incorrectly in the first place because the wrong data will be written back to the file. During testing, this means that even when the reading code has been corrected, it will still read the erroneous data that was written from a previous test run.
My preference in this situation is would be to isolate all the reading and writing code for "game.txt" inside the Game class (which makes it easier to verify that the reading and writing formats are identical) and only write the code to write the data back out once I'd written and tested the reading code, which would avoid this Gotcha.
Here is my main class:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.io.*;
import java.lang.Process.*;
public class FTP {
public static void main (String []args)
{
Runnable runner = new Runnable(){
public void run()
{
LookAndFeel nimbusLook = new LookAndFeel();
nimbusLook.NimbusLookAndFeel();
JFrame frame = new JFrame("BNA FTP Diagnose");
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(540, 420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 150);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
final JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
JMenu helpMenu = new JMenu("Help");
menuBar.add(new JPanel());
menuBar.add(helpMenu);
final JMenuItem aboutMenuItem = new JMenuItem("About");
helpMenu.add(aboutMenuItem);
JPanel titlePanel = new JPanel(new BorderLayout());
frame.add(titlePanel, BorderLayout.NORTH);
JLabel titleLabel = new JLabel("FTP Diagnose", JLabel.CENTER);
titleLabel.setFont(new Font(null, Font.BOLD, 14));
titleLabel.setForeground(Color.BLUE);
titlePanel.add(titleLabel);
JPanel gridPanel = new JPanel(new GridLayout(1, 1));
frame.add(gridPanel);
JPanel vendorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
gridPanel.add(vendorPanel);
final String vendor [] = {"LLesiant" ,"WK-CCH", "Proquest", "Notes", "Research Institute of America", "Thomson",
"BNAI PDF Processing", " TM Portfolios to Indexing", "Postscript to PRODLOGIN1", "www.firstdoor.net", "psp.bna.com", "WEST", "LexisNexis", "McArdle Printing Company",
"Breaking News Email", "Ex Libris", "Pandora", "Bloomberg Law", "Acquire Media Site 1", "Acquire Media Site 2", "Quicksite", "QA Quicksite"};
final JComboBox vendorList = new JComboBox(vendor);
vendorPanel.add(vendorList);
JPanel diagnoseButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
gridPanel.add(diagnoseButtonPanel);
final JButton diagnoseButton = new JButton("Diagnose");
diagnoseButtonPanel.add(diagnoseButton);
JPanel centerPanel = new JPanel(new BorderLayout());
frame.add(centerPanel, BorderLayout.SOUTH);
JPanel commandPanel = new JPanel(new GridLayout(1, 0));
centerPanel.add(commandPanel);
final JTextArea commandResultArea = new JTextArea(7, 0);
JScrollPane scroll = new JScrollPane(commandResultArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
commandPanel.add(scroll);
commandResultArea.setEditable(false);
ActionListener buttonListener = new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
int selectedIndex = vendorList.getSelectedIndex();
String llesiant = "ftp.llesiant.com";
String wkCCH = "FTP1.cch.com";
String proquest = "ftp.proquest.com";
String notes = "notes5.bna.com";
//String lineThree = null;
CommandClass readCommand = new CommandClass();
if (selectedIndex == 0)
{
commandResultArea.setText(readCommand.getCommand(llesiant)); //these return strings
}
else if (selectedIndex == 1)
{
commandResultArea.setText(readCommand.getCommand(wkCCH));
}
else if (selectedIndex == 2)
{
commandResultArea.setText(readCommand.getCommand(proquest));
}
else if (selectedIndex == 3)
{
commandResultArea.setText(readCommand.getCommand(notes));
}
}
};
diagnoseButton.addActionListener(buttonListener);
ActionListener exitListener = new ActionListener (){
public void actionPerformed(ActionEvent el)
{
if (el.getSource()== exitMenuItem)
{
JOptionPane.showMessageDialog(null, "FTP Program will exit now!");
System.exit(0);
}
}
};
exitMenuItem.addActionListener(exitListener);
ActionListener aboutListener = new ActionListener()
{
public void actionPerformed(ActionEvent al)
{
if (al.getSource()== aboutMenuItem)
{
JOptionPane.showMessageDialog(null, "This Software was made for Editors to. \nDiagnose BNA Bloomberg client FTP site.");
}
}
};
aboutMenuItem.addActionListener(aboutListener);
}
};
EventQueue.invokeLater(runner);
}
}
Here is my Look and feel class:
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class LookAndFeel {
public void NimbusLookAndFeel()
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
}
}
Here is my CommandClass:
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class CommandClass {
public String getCommand(String ftpSite){
String command = "ftp ";
StringBuffer output = new StringBuffer();
try{
Process p = Runtime.getRuntime().exec(command +ftpSite);
InputStreamReader ir = new InputStreamReader (p.getInputStream());
int outputChar = 0;
while((outputChar = ir.read()) != -1){
output.append((char)outputChar);
if(!ir.ready()){ // If the next read is not guarenteed, come out of loop.
break;
}
}
ir.close();
JOptionPane.showMessageDialog(null, "FTP is connected");
}catch (IOException e){
e.printStackTrace();
}
return output.toString();
}
}
I have this FTP GUI which suppose to connect to an FTP site and return the status. If it's connected it shows the connection prompt.
I got the JTextArea to show the message when the FTP connection is established, but when it's not connected to the ftp site such as my 4th ftp site which is notes5.bna.com it freezes the program. Also a small problem is if you have the program FTP to a site like this "shlfsdklaflkhasdlhfas". It returns the ftp site is not found only after the JOptionPane shows that FTP is connected. I am not sure what's wrong with it.
The reason that notes5.bna.com is freezing is that the site is not responding to FTP connection requests. As you are simply using Runtime#exec to make the connection, this will block indefinitely for a response. Consider using a 3rd party FTP client such as Apache FTPClient which allows you to specify a connection timeout.
A related issue is that some sites are requesting a username & password for access. Again FTPClient allows you to provide login details.
Last but not least, don't let heavyweight non-UI tasks freeze your Swing application. Swing has mechanisms to deal with these such as SwingWorker objects.
Related Swingworker Network Example
I am looking for a quick fix to this problem I have: Here is my code:
import java.awt.Dimension;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory{
public static void main(String args[]) throws IOException{
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100,30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
String housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Basically After I wrote this code, Eclipse told me I had to change the modifier of housetype, to final. Which truly won't do, because I need to be a changing value if its going to go trough different records.
PLEASE HELP ME! D:
You have several options here:
The quickest would be to do what Eclipse tells you, actually it is Java that tells you that. In order to be able to use method local variables inside inner classes inside the method, the variables must be final.
Another option is to declare the housetype variable as an instance variable, immediately after the class definition. But, using it in the static main method means that the variable needs to be static too, which makes it a class variable.
Another one would be to keep the code as you have, but declare an extra variable like below and then use the house variable inside the inner class instead of housetype. See the entire code below:
public class Directory {
public static void main(String args[]) throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
There are even more options, but these are the quickest.
One workaround is that you create a new method inside your class Directory that is being called from the ActionListener and does your tasks:
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if(searchquery.equals(housetype)){
System.out.println("We Have Found A Record!!");
}
}
and then call it like this:
public void actionPerformed(ActionEvent ae)
{
searchButtonAction();
});
This only works if you create a constructor in the class and call it from the main method. Furthermore all variables used inside the searchButtonAction method must be class visible.
Full code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory {
private final JTextField searchfield = new JTextField();
private final JProgressBar searchprogress = new JProgressBar();
private String housetype;
public Directory() throws IOException {
JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
searchfield.setPreferredSize(new Dimension(100, 30));
searchprogress.setPreferredSize(new Dimension(200, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
BufferedReader br = new BufferedReader(new FileReader("test1.txt"));
housetype = br.readLine();
String housenumber = br.readLine();
String housestreet = br.readLine();
String housepostal = br.readLine();
String houseplace = br.readLine();
String seperation = br.readLine();
/* Finish Buffered Reader */
/* Start Content Code */
JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchButtonAction();
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private void searchButtonAction() {
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
if (searchquery.equals(housetype)) {
System.out.println("We Have Found A Record!!");
}
}
public static void main(String args[]) throws IOException {
new Directory();
}
}
I've been trying for hours to trying to load the contents of a text file into a JTextArea. I'm able to load the text into the console but not into the JTextArea I don't know what I'm doing wrong. Any help is appreciated thanks!
The class for the program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class LoadClass extends JPanel
{
JPanel cards;
private JPanel card1;
private JTextArea textarea1;
private int currentCard = 1;
private JFileChooser fc;
public LoadClass()
{
Font mono = new Font("Monospaced", Font.PLAIN, 12);
textarea1 = new JTextArea();
textarea1.setFont(mono);
card1 = new JPanel();
card1.add(textarea1);
cards = new JPanel(new CardLayout());
cards.add(card1, "1");
add(cards, BorderLayout.CENTER);
setBorder(BorderFactory.createTitledBorder("Animation here"));
setFont(mono);
}
public void Open()
{
textarea1 = new JTextArea();
JFileChooser chooser = new JFileChooser();
int actionDialog = chooser.showOpenDialog(this);
if (actionDialog == JFileChooser.APPROVE_OPTION)
{
File fileName = new File( chooser.getSelectedFile( ) + "" );
if(fileName == null)
return;
if(fileName.exists())
{
actionDialog = JOptionPane.showConfirmDialog(this,
"Replace existing file?");
if (actionDialog == JOptionPane.NO_OPTION)
return;
}
try
{
String strLine;
File f = chooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(f));
while((strLine = br.readLine()) != null)
{
textarea1.append(strLine + "\n");
System.out.println(strLine);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
}
The Main Program
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LoadMain extends JFrame
{
private LoadClass canvas;
private JPanel buttonPanel;
private JButton btnOne;
public LoadMain()
{
super("Ascii Art Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
canvas = new LoadClass();
buildButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
add(canvas, BorderLayout.CENTER);
pack();
setSize(800, 800);
setVisible(true);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
btnOne = new JButton("Load");
buttonPanel.add(btnOne);
btnOne.addActionListener(new btnOneListener());
}
private class btnOneListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btnOne)
{
canvas.Open();
}
}
}
public static void main(String[] args)
{
new LoadMain();
}
}
public void Open()
{
textarea1 = new JTextArea();
Change that to:
public void Open()
{
//textarea1 = new JTextArea(); // or remove completely
The second field created is confusing things.