javac cannot find this class : StreamedTextArea() which I assumed was part of java.awt.*. If I need to write it myself then can anyone offer me some advice. The only references to it online were from ~1999 which inclines me to think it is not a Sun class but one I must write myself. Also in this code (which is from a textbook) they use Frame instead of JFrame. Is this deprecated, how should this application be written nowadays ? Please I have tried finding the answers myself online but to no avail.
The application :
//URLViewer.java
//This is a simple application that provides a window in which you can view the
//contents of a URL.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class URLViewer extends Frame implements WindowListener, ActionListener {
TextField theURL = new TextField();
Button loadbutton = new Button("load");
StreamedTextArea theDisplay = new StreamedTextArea();
public URLViewer() {
super ("URL Viewer");
}
public void init() {
this.add("North", theURL);
this.add("Center", theDisplay);
Panel south = new Panel();
south.add(loadbutton);
this.add("South", south);
theURL.addActionListener(this);
this.addWindowListener(this);
this.setLocation(50, 50);
this.pack();
this.show();
}
public void actionPerformed (ActionEvent evt) {
try {
URL u = new URL (theURL.getText());
InputStream in = u.openStream();
OutputStream out = theDisplay.getOutputStream();
StreamCopier.copy(in, out);
in.close();
out.close();
} catch (MalformedURLException ex) {theDisplay.setText("Invalid URL");}
catch (IOException ex) {theDisplay.setText("Invalid URL");}
}
public void windowClosing (WindowEvent e) {
this.setVisible(false);
this.dispose();
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public static void main (String[] args) {
URLViewer me = new URLViewer();
me.init();
}
}
And StreamCopier :
import java.io.*;
public class StreamCopier {
public static void main (String[] args) {
try {
copy (null, null);
} catch (IOException e) {System.err.println(e);}
}
public static void copy (InputStream in, OutputStream out) throws IOException {
//do not allow other threads to read from the input or
//write to the output while copying is taking place.
synchronized (in) {
synchronized (out) {
byte [] buffer = new byte [256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
}
}
}
} //end copy()
}
Here is StreamedTextArea.java. I found it on this page, which also has code that matches your StreamCopier class. This page also contains information on that site.
Related
I have made this simple program which opens a frame and in which you can write in the textarea given.You can count the number of words and characters using count button or you could save the text of the textarea to the local file-"trial.txt"
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class trial extends Frame
{
static TextArea ta=new TextArea("Welcome");
static Label l1=new Label("Words:");
static Label l2=new Label("Characters:");
static Button b=new Button("Count");
static Button save=new Button("Save");
static BufferedOutputStream bos;
trial()
{
//Setting position
ta.setBounds(300,300,300,300);
l1.setBounds(50,50,100,100);
l2.setBounds(50,200,100,100);
b.setBounds(650,300,50,50);
save.setBounds(650,400,50,50);
//Setting up file for saving
try {
bos=new BufferedOutputStream(new FileOutputStream("trial.txt"));
} catch (Exception e) {
e.printStackTrace();
}
save.addActionListener(new Save());
//Adding the components
this.add(ta);
this.add(l1);
this.add(l2);
this.add(b);
this.add(save);
//adding actionlistener to button
b.addActionListener(new actionlistener());
//setting up frame
this.setSize(1000,1000);
this.setLayout(null);
this.setVisible(true);
}
public static class actionlistener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
String words[]=text.split("\\s");
l1.setText("Words:"+words.length);
l2.setText("Characters:"+text.length());
}
}
public static class Save implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
String text=ta.getText();
byte[] arr=text.getBytes();
try
{
bos.write(arr);
bos.flush();
} catch (IOException f)
{
f.printStackTrace();
}
}
}
public static void main(String args[])
{
trial ttt=new trial();
}
}
But this is not working. The count button is working fine but the save button does not work. I do not understand what the error is. Your help will be greatly appreciated.
*Edit:It is working now.Just moved the location of the txt file to the same as of the location of the java file and it started working.Thanks for your help.
When opening a file in a JTree, the tree's preferred size changes but his propertyChangeListener doesn't detect it (but if you change it calling setPreferredSize is able to detect it). Is it my code that is wrong or is javax.swing bugged? If this isn't the way of doing this how should I do it. I tested the code with maximumSize as well.
Here is my code, you shouldn't need any external resources:
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class MyJFrame extends JFrame
{
public MyJFrame()
{
add(new JTree()
{
{
addPropertyChangeListener("preferredSize",
new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt)
{
System.out.println("preferred size changed");
}
});
new Thread()
{
public void run()
{
while(true)
{
System.out.println("preferred size = "+getPreferredSize());
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
}.start();
}
});
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJFrame();
}
}
I am getting a cannot find symbol-method open(java.lang.String) error message. I dint know were i have gone wrong. The whole program works fine. I just have this one error. Its for a project and it needs to be submitted in 2 days. I hope you can answer me fast.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class DeviceON extends MIDlet implements CommandListener {
private Command exitCommand; // The exit command
private Display display; // The display for this MIDlet
public String btConnectionURL ;
public OutputStream out ;
private Form mainForm;
private Alert conf ;
private Command tryagainCommand ;
public StreamConnection Connector;
public interface StreamConnection{}
public DeviceON() {
display = Display.getDisplay(this);
conf = new Alert("Sucessfull","Device is ON.\n\nDevice Control",null,AlertType.CONFIRMATION);
exitCommand = new Command("Exit", Command.EXIT, 0);
tryagainCommand = new Command("Try Again",Command.OK,1);
}
public void startApp() {
try{
mainForm = new Form ("Bluetooth Device Control");
btConnectionURL = "btspp://" + "0019A40244C5" + ":1;authenticate=true;encrypt=false;master=false";
StreamConnection connection = (StreamConnection)Connector.open(btConnectionURL);
out = connection.openOutputStream();
out.write(170);
out.write(1) ;
out.flush() ;
conf.setTimeout(4000);
display.setCurrent(conf, mainForm);
try {
Thread.sleep(4000);
} catch (Exception e) {}
destroyApp(false);
notifyDestroyed();
}
catch (IOException ioe) {
mainForm = new Form ("Bluetooth Device Control");
ioe.printStackTrace();
mainForm = new Form ("Bluetooth Device Control");
mainForm.append("Connection Failed");
mainForm.addCommand(tryagainCommand) ;
mainForm.addCommand(exitCommand);
display.setCurrent(mainForm);
mainForm.setCommandListener(this);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
else {
if (c == tryagainCommand)
startApp() ;
}
}
}
Instead of
(StreamConnection)Connector.open(btConnectionURL);
Do
((StreamConnection)Connector).open(btConnectionURL);
Cast connector before calling method
I have a set of JButtons, each of which opens a separate YouTube video webpage. When first running the program, I can click on any ONE button and get the video page. When I try to get another video page with a button click, it doesn't work - in fact, all the buttons are deactivated. This is the case whether or not I close the video webpage.
How can I keep all the buttons activated? Thanks in advance.
Here's the code for reference. The button links and tags are populated from a text file.
//import statements
public class VideoRecord extends JFrame {
private File videoRecordFile;
public VideoRecord() throws FileNotFoundException {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
setSize(new Dimension(500, 500));
videoRecordFile = new File("videorecord.txt");
getButtons();
pack();
}
public void getButtons() throws FileNotFoundException {
Scanner input = new Scanner(videoRecordFile);
while (input.hasNextLine()) {
Scanner lineInput = new Scanner(input.nextLine());
while (lineInput.hasNext()) {
final String urlString = lineInput.next();
String buttonText = lineInput.next();
JButton btn = new JButton(buttonText);
add(btn);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URL videoURL = new URL(urlString);
URLConnection videoConnection = videoURL.openConnection();
videoConnection.connect();
openWebpage(videoURL);
}
catch (MalformedURLException mue) {}
catch (IOException ioe) {}
setEnabled(false);
}
});
}
}
}
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException {
VideoRecord vr = new VideoRecord();
}
}
Take a second to look at you code...
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URL videoURL = new URL(urlString);
URLConnection videoConnection = videoURL.openConnection();
videoConnection.connect();
openWebpage(videoURL);
}
catch (MalformedURLException mue) {}
catch (IOException ioe) {}
setEnabled(false);
}
});
When you click a button you call setEnabled(false);...
This has actually disable the frame, not the button that was clicked...
Try using ((JButton)e.getSource()).setEnabled(false) instead
Don't throw away you Exceptions blindly, they provide important and useful information that can help solve problems
So I am making this code to write to a file based on user clicks. The only problem I have, is that I get an error on "public class prog". The prog name is where I get the error: It says: The type prog must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent). When I do the quickfix of adding the uninherited methods, it adds the action listener method to the end of my code but with nothing in it. If I already have action listeners in the program, why does it tell me I need to implement them? And why when I add it at the end, does it work fine even though nothing is in it?
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.*;
public class prog extends JFrame implements ActionListener {
//create newLine
final String newLine = System.getProperty("line.separator");
//create buttons
JPanel row1 = new JPanel();
JButton oneLeft = new JButton("oneLeft");
JButton oneRight = new JButton("oneRight");
JPanel row2 = new JPanel();
JButton twoLeft = new JButton("twoLeft");
JButton twoRight = new JButton("twoRight");
JPanel row3 = new JPanel();
JButton threeLeft = new JButton("threeLeft");
JButton threeRight = new JButton("threeRight");
public prog() {
super("Prog");
setLookAndFeel();
setSize(400, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout = new GridLayout(3, 2);
setLayout(layout);
//create outStream for writing to file
try {
final File numClicks = new File("numClicks.properties");
final FileOutputStream outStream = new FileOutputStream(numClicks);
//add Listeners
oneLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "oneLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
oneRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "oneRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
twoLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "twoLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
twoRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "twoRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
threeLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "threeLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
threeRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "threeRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
} catch (IOException ioe) {
System.out.println("The file could not be written.");
}
row1.add(oneLeft);
row1.add(oneRight);
row2.add(twoLeft);
row2.add(twoRight);
row3.add(threeLeft);
row3.add(threeRight);
add(row1);
add(row2);
add(row3);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
//ignore error
}
}
void write(FileOutputStream stream, String output) throws IOException {
output = output + newLine;
byte[] data = output.getBytes();
stream.write(data, 0, data.length);
}
public static void main(String[] args) {
prog progApp = new prog();
}
}
Your class shouldn't implement ActionListener. Instead of writing a top-level class that implements the interface, you're writing a bunch of little inline classes (called anonymous inner classes) that do this work for you when you say new ActionListener().
You implement ActionListener it, but you don't actually implement the required methods (i.e., actionPerformed()). Therefore your class is invalid to the compiler.
You need a method like:
#Override
public void actionPerformed(ActionEvent e) {
// ...
}
The way an interface works is that it defines what the classes that implements it have to... well... implement. That way any other process can treat it as an ActionListener and know that certain methods have been defined.
Just another way Java tries to make polymorphism your friend.
To address something from the comment below, it's actually not that uncommon to see a class implement an interface (like KeyListener) and define the method without even using it.
For example, KeyListener requires you to implement three different methods:
public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);
Let's say I only really care about keyPressed. Then my class might look something like this:
public class MyKeyListener implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
// do stuff
}
#Override
public void keyReleased(KeyEvent e){}
#Override
public void keyTyped(KeyEvent e){}
}