Web scraping console output in Swing GUI [duplicate] - java

I have posted two pieces of code below. Both codes work fine individually. Now, when I run the file Easy, and click on the "Start" button, I want the class AddNumber to be implemented. I mean to say that, instead of the AddNumber running on the console, is there any way I could make AddNumber run in the JTextArea i have created in the first class upon clicking the "Start" button? I thought maybe by action listener?(the way we do in case of buttons) But I'm not sure. Is there any other way to make my JTextArea act as a console for the other .java files?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Easy extends JFrame{
JTextArea text=new JTextArea();
JPanel panel=new JPanel(new GridLayout(2,2));
JButton button1 =new JButton("Start");
public Easy(){
panel.add(text);
panel.add(button1);
add(panel,BorderLayout.CENTER);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
//add code to call the other class and make the JTextArea act as a console
}
});
}
public static void main(String arg[]){
Easy frame=new Easy();
frame.setSize(300,100);
frame.setVisible(true);
}
}
The second class:
import java.util.Scanner;
class AddNumber
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter two numbers to be added ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = x + y;
System.out.println("Sum of entered numbers = "+z);
}
}
I have seen a few posts talking about PrintStream..but i don't think that applies here.
Please help me out. Thanks :)
UPDATE: well i found this link: http://www.codeproject.com/Articles/328417/Java-Console-apps-made-easy#HowtousethisJavaConsole1 and it works in the sense that it shows "Enter two numbers to be added "...but where can the user provide his input?
EDIT: I just had to make a reference of the console in the main method of my class...and it works... well, not exactly as i would've wished to..but partly..the input still has to go from the terminal of the IDE..

If you do a Google search for: "stdout JTextArea", you will a couple of links to solve your problem.
http://www.coderanch.com/t/458147/GUI/java/Redirect-output-stderr-stdout-JTextArea
Redirecting System.out to JTextPane
http://www.jcreator.com/forums/index.php?showtopic=773
In the last link, buddybob extends java.io.OutputStream to print standard output to his JTextArea. I included his solution below.
TextAreaOutputStream.java
/*
*
* #(#) TextAreaOutputStream.java
*
*/
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
/**
* An output stream that writes its output to a javax.swing.JTextArea
* control.
*
* #author Ranganath Kini
* #see javax.swing.JTextArea
*/
public class TextAreaOutputStream extends OutputStream {
private JTextArea textControl;
/**
* Creates a new instance of TextAreaOutputStream which writes
* to the specified instance of javax.swing.JTextArea control.
*
* #param control A reference to the javax.swing.JTextArea
* control to which the output must be redirected
* to.
*/
public TextAreaOutputStream( JTextArea control ) {
textControl = control;
}
/**
* Writes the specified byte as a character to the
* javax.swing.JTextArea.
*
* #param b The byte to be written as character to the
* JTextArea.
*/
public void write( int b ) throws IOException {
// append the data as characters to the JTextArea control
textControl.append( String.valueOf( ( char )b ) );
}
}
The TextAreaOutputStream extends the java.io.OutputStream class
and overrides its write(int) method overload, this class uses a
reference to a javax.swing.JTextArea control instance and then
appends output to it whenever its write( int b ) method is called.
To use the TextAreaOutputStream class, [yo]u should use:
Usage
// Create an instance of javax.swing.JTextArea control
JTextArea txtConsole = new JTextArea();
// Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a
// PrintStream around it to support the println/printf methods.
PrintStream out = new PrintStream( new TextAreaOutputStream( txtConsole ) );
// redirect standard output stream to the TextAreaOutputStream
System.setOut( out );
// redirect standard error stream to the TextAreaOutputStream
System.setErr( out );
// now test the mechanism
System.out.println( "Hello World" );

Related

Constructor must call super() or this()

Can anyone help me with the following error report (for the code at the bottom):
Exception in thread "AWT-EventQueue-0" java.lang.VerifyError: Constructor must call super() or this() before return in method org.jfree.ui.RectangleInsets.<init>()V at offset 0
at org.jfree.chart.axis.Axis.<clinit>(Axis.java:153)
at org.jfree.chart.StandardChartTheme.<init>(StandardChartTheme.java:233)
at org.jfree.chart.StandardChartTheme.<init>(StandardChartTheme.java:319)
at org.jfree.chart.ChartFactory.<clinit>(ChartFactory.java:231)
at odesolver.ODESolver.createGraph(ODESolver.java:81)
at odesolver.ODESolver.<init>(ODESolver.java:35)
at odesolver.ODESolver$2.run(ODESolver.java:105)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
BUILD SUCCESSFUL (total time: 2 seconds)
which relates to the following 3 lines of the code:
ODESolver.java:81
JFreeChart chart = ChartFactory.createXYLineChart(
ODESolver.java:35
createGraph();
ODESolver.java:105
new ODESolver(); // Let the constructor do the job
Whole program:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package odesolver;
/**
*
* #author User
*/
import java.awt.*; // Using AWT containers and components
import java.awt.event.*; // Using AWT events and listener interfaces
import javax.swing.*; // Using Swing components and containers
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.ChartPanel;
import org.jfree.data.general.Series;
// A Swing GUI application inherits the top-level container javax.swing.JFrame
public class ODESolver extends JFrame {
private JTextField tfInput, tfOutput;
private int numberIn; // input number
private int sum = 0; // accumulated sum, init to 0
/** Constructor to setup the GUI */
public ODESolver() {
// Retrieve the content-pane of the top-level container JFrame
// All operations done on the content-pane
Container cp = getContentPane();
cp.setLayout(new GridLayout(2, 2, 5, 5));
createGraph();
add(new JLabel("Enter an Integer: "));
tfInput = new JTextField(10);
add(tfInput);
add(new JLabel("The Accumulated Sum is: "));
tfOutput = new JTextField(10);
tfOutput.setEditable(false); // read-only
add(tfOutput);
// Allocate an anonymous instance of an anonymous inner class that
// implements ActionListener as ActionEvent listener
tfInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the String entered into the input TextField, convert to int
numberIn = Integer.parseInt(tfInput.getText());
sum += numberIn; // accumulate numbers entered into sum
tfInput.setText(""); // clear input TextField
tfOutput.setText(sum + ""); // display sum on the output TextField
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked
setTitle("ODE Accumulator"); // "this" Frame sets title
setSize(350, 120); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
private JPanel createGraph() {
JPanel panel = new JPanel();
XYSeries series = new XYSeries("MyGraph");
series.add(0, 1);
series.add(1, 2);
series.add(2, 5);
series.add(7, 8);
series.add(9, 10);
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
JFreeChart chart = ChartFactory.createXYLineChart(
"XY Chart",
"x-axis",
"y-axis",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
ChartPanel chartPanel = new ChartPanel(chart);
panel.add(chartPanel);
return panel;
}
/** The entry main() method */
public static void main(String[] args) {
// Run the GUI construction in the Event-Dispatching thread for thread-safety
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ODESolver(); // Let the constructor do the job
}
});
}
}
Maybe the problem is that there are files in ODESolver, src and lib with errors, as netbeans reports (see screenshot below). I don't know which files are upposed to have errors though, as none of then have an exclamation mark on them, as they usually do of they have errors.
You appear to be running an old version of JFreeChart which produces this error. Upgrade to version 1.0.13 as found here
problem was solved by adding the jar files to the classpath, rather than the folder containing them
The various constructors of JFrame do important initialisation work, that any JFrame requires. Therefore, every JFrame that is ever created must have one of those constructors called. But because an ODESolver is also a JFrame, that applies to ODESolver objects too.
Fortunately, the Java language enforces this. We can't create an ODESolver, without one of the JFrame constructors getting called. The way it enforces it is by requiring every ODESolver constructor to be mapped to a JFrame constructor.
When we create an ODESolver, one of the ODESolver constructors will get called. But that constructor must specify which JFrame constructor will get called. The way it does that is by doing one of the following.
specifying explicitly which JFrame constructor to use, via a call to super(), with or without some arguments;
calling another ODESolver constructor, via a call to this(), with or without some arguments.
In either case, the call to super() or this() must be the first line of the ODESolver constructor.

How to show input of JTextField in JLabel ? how to fix error in reflection ?

i have to do this: i have one JTextField and button. And when i write to that TextField output must show result in JLabel.
Asks the user to provide the name of a class.
Uses Class.forName() to get an access to Java Reflection API.
Creates a new instance (i.e. object) of the class using the default constructor.
Finds and displays all fields of the class in the form including inherited fields:
field_type field_name: (field_value(JTextField))(Set(Button))
field_value must be a textbox, so that the user can change the value by pressing ‘Set’ button. The new value must be updated to the object. If the field contains values of complex types (objects, collections etc.) then the textbox and ‘Set’ button should not be created.
Finds and displays all methods of the class including inherited methods:
return_type method_name (param_type1 (param_value1(JTextField)), param_type2(param_value2(JTextField)) , ..) (Invoke(Button))
If a method has parameters of complex types (objects, collections etc.) then only parameters’ types are displayed, param_values’ textboxes and ‘invoke’ button are skipped.
When the user presses “invoke” button, the application must invoke the method. Make sure that if the method alters the fields’ values these changes are displayed.
and my code here:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.StringBuffer;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ReflectionTest {
private String class_name = "java.lang.StringBuffer";
public ReflectionTest() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
JLabel jl1 = null, jl2, jl3, jl4;
JFrame jf = new JFrame("New");
JPanel jp = new JPanel();
JTextField jtf = new JTextField(20);
JButton jb = new JButton("Press");
jtf.setVisible(true);
jp.add(jb);
jp.add(jtf);
jf.add(jp);
jf.setVisible(true);
jf.setSize(400, 550);
jf.setResizable(false);
String text = jtf.getText().toString();
Class cs = Class.forName(text);
jb.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
// THIS CODE IS EXECUTED WHEN RETURN IS TYPED
}
}
);
for(Constructor c: cs.getConstructors()){
for(Class p: c.getParameterTypes())
System.out.print(p.getName()+" ");
System.out.println();
}
Constructor c = cs.getConstructor(new Class[]{String.class});
Object list = c.newInstance("AA");
Field pub_fields[] = cs.getFields();
Field all_fields[] = cs.getDeclaredFields();
System.out.println("Public fields:");
for(Field f:pub_fields){
//Showing public fields
System.out.println();
jl1 = new JLabel(f.getType().getName() + " " + f.getName());
jp.add(jl1);
jl1.setVisible(true);
}
System.out.println("All declared fields:");
for(Field f:all_fields){
//Showing all declared fields
jl2 = new JLabel(f.getType().getName() + " "+f.getName()+" ");
jp.add(jl2);
jl2.setVisible(true);
f.setAccessible(true);
Object val = f.get(list);
if (val != null){
//System.out.println(val.toString());
jl3 = new JLabel(val.toString());
jp.add(jl3);
jl3.setVisible(true);
System.out.println();
}
else{
System.out.println("NULL");
//f.get(list1);
}
}
}
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) {
try{
// TODO Auto-generated method stub
new ReflectionTest();
}
catch (Exception e){
e.printStackTrace();
}
}
}
and i have error. Eclipse show it in this line:
Class cs = Class.forName(text);
If you test the text String before the exception occurs, for instance by printing it out:
System.out.printf("text = \"%s\"%n", text);
Class cs = Class.forName(text);
Which returns:
text = ""
java.lang.ClassNotFoundException:
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at pkg.ReflectionTest.<init>(ReflectionTest.java:42)
at pkg.ReflectionTest.main(ReflectionTest.java:102)
You'll see that the text String is empty, "". This is because you have no text when you call the Class cs = Class.forName(text); since it's being called before the GUI has been rendered, much less give the user time to enter text. Only call this in code that is called due to a user-generated event of some sort such as an ActionListener's actionPerformed method.
In other words, add the critical code to where in your own commment you state you should add the code:
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// THIS CODE IS EXECUTED WHEN RETURN IS TYPED // *********!!!!
}
});
And I second the comment that you should show any and all information about the exception. Please don't make us guess what the problem is.
Edit
Also you will have a problem with using local variables, including the JLabels and JTextField, inside of the anonymous inner listener class. The easiest and best way to solve this is to make the variables that need to be accessed in this listener private class fields. So remove their declarations from the constructor and instead move them to the class itself.
Is it really an error or a "yellow" line? Class is a parametized type and if you do not use generics then eclipse will show a warning.
To eliminate such a warning, simply do a
Class<?> cs = Class.forName(text);
The wildcard is ok because you really don't know which "type" of Class you're going to load.

Drag and Drop file path to Java Swing JTextField

Using this question, I created the class below, which handles drag and drop of files to a JTextField. The point of the application is to be able to drag a file into the text field, and have the text field's text set to the file's path (you can see the goal in the code pretty clearly).
My problem is the below code does not compile. The compilation error states Cannot refer to non-final variable myPanel inside an inner class defined in a different method. I haven't worked much with inner classes, so can seomeone show me how to resolve the error and get the code to behave as designed?
Code:
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.util.List;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JTextArea myPanel = new JTextArea();
myPanel.setDropTarget(new DropTarget() {
public synchronized void drop(DropTargetDropEvent evt) {
try {
evt.acceptDrop(DnDConstants.ACTION_COPY);
List<File> droppedFiles = (List<File>) evt
.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
for (File file : droppedFiles) {
/*
* NOTE:
* When I change this to a println,
* it prints the correct path
*/
myPanel.setText(file.getAbsolutePath());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
JFrame frame = new JFrame();
frame.add(myPanel);
frame.setVisible(true);
}
}
As the error message says, myPanel needs to be defined as final.
final JTextArea myPanel = new JTextArea();
This way the inner class can be given one reference pointer to the variable instance without concern that the variable might be changed to point to something else later during execution.
Another option is to declare the variable static.
static JTextArea myPanel = new JTextArea();

Simple Web Service adding two numbers

I have created a simple Webservice function as shown below;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ws;
import javax.jws.WebService;
/**
*
* #author Joe
*/
#WebService()
public class Add2Int {
public int add(int a, int b) {
return (a+b);
}
}
and I have created a very simple gui that allows the user to enter 2 numbers and which should output the result however this does not work? I tried it without the gui and it works but when i build the gui it does not work? here is my code for that side of things
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myjavawsclient;
//import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* #author Joe
*/
public class Calculator extends JFrame implements FocusListener {
JTextField value1 = new JTextField("", 5);
JLabel plus = new JLabel("+");
JTextField value2 = new JTextField("",5);
JLabel equals = new JLabel("=");
JTextField sum = new JTextField("", 5);
public Calculator() {
super("The Calculator");
setSize(350,90);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
setLayout(flow);
// add the listners
value1.addFocusListener(this);
value2.addFocusListener(this);
// set up sum field
sum.setEditable(true);
//add componets
add(value1);
add(plus);
add(value2);
add(equals);
add(sum);
setVisible(true);
}
public void focusGained(FocusEvent event){
try { // Call Web Service Operation
ws.Add2IntService service = new ws.Add2IntService();
ws.Add2Int port = service.getAdd2IntPort();
// TODO initialize WS operation arguments here
int result = 0;
int result2 = 0;
result = Integer.parseInt(value1.getText());
result2 = Integer.parseInt(value2.getText());
int total = port.add(result, result2);
sum.setText("" +total);
//float plusTotal = Float.parseFloat(value1.getText()) +
Float.parseFloat(value2.getText());
} catch (Exception ex) {
// TODO handle custom exceptions here
//value1.setText("0");
//value2.setText("0");
//sum.setText("0");
}
}
public void focusLost(FocusEvent event){
focusGained(event);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Calculator frame = new Calculator();
}
}
I am not getting any errors I am just not getting any result from the 2 numbers, for example 1+1=2 but with my application it allows the user to enter 1 + 1 = ? but where the question mark is nothing gets shown.
I was wondering if anyone could solve this problem for me. Oh and I am using NetBeans and GlassFish App server with WSDL
Joe
You should declare add as a webmethod.
try following:
#WebMethod public int add(int a, int b){
return (a+b);
}
My Fault! I forgot to start the App Server

Rendering HTML in Java

I am trying to create a help panel for an application I am working on. The help file as already been created using html technology and I would like it to be rendered in a pane and shown. All the code I have seen shows how to render a site e.g. "http://google.com". I want to render a file from my pc e.g. "file://c:\tutorial.html"
This is the code i have, but it doesn't seem to be working.
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Container;
import java.io.IOException;
import static java.lang.System.err;
import static java.lang.System.out;
final class TestHTMLRendering
{
// ------------------------------ CONSTANTS ------------------------------
/**
* height of frame in pixels
*/
private static final int height = 1000;
/**
* width of frame in pixels
*/
private static final int width = 1000;
private static final String RELEASE_DATE = "2007-10-04";
/**
* title for frame
*/
private static final String TITLE_STRING = "HTML Rendering";
/**
* URL of page we want to display
*/
private static final String URL = "file://C:\\print.html";
/**
* program version
*/
private static final String VERSION_STRING = "1.0";
// --------------------------- main() method ---------------------------
/**
* Debugging harness for a JFrame
*
* #param args command line arguments are ignored.
*/
#SuppressWarnings( { "UnusedParameters" } )
public static void main( String args[] )
{
// Invoke the run method on the Swing event dispatch thread
// Sun now recommends you call ALL your GUI methods on the Swing
// event thread, even the initial setup.
// Could also use invokeAndWait and catch exceptions
SwingUtilities.invokeLater( new Runnable()
{
/**
* } fire up a JFrame on the Swing thread
*/
public void run()
{
out.println( "Starting" );
final JFrame jframe =
new JFrame( TITLE_STRING + " " + VERSION_STRING );
Container contentPane = jframe.getContentPane();
jframe.setSize( width, height );
contentPane.setBackground( Color.YELLOW );
contentPane.setForeground( Color.BLUE );
jframe.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
try
{
out.println( "acquiring URL" );
JEditorPane jep = new JEditorPane( URL );
out.println( "URL acquired" );
JScrollPane jsp =
new JScrollPane( jep,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
contentPane.add( jsp );
}
catch ( IOException e )
{
err.println( "can't find URL" );
contentPane.add( new JLabel( "can't find URL" ) );
}
jframe.validate();
jframe.setVisible( true );
// Shows page, with HTML comments erroneously displayed.
// The links are not clickable.
}
} );
}// end main
}// end TestHTMLRendering
Rendering HTML in Swing is problematic. Swing components have some native support for HTML but it's not even HTML4. It's (limited!) HTML 3.2. If you use a different desktop library API you'll have much better options
WebKit for SWT (ver. 0.6) for the Eclipse Standard Widget Tookit is an excellent option. As the name suggests, it plugs the WebKit rendering engine (which powers Chrome and Safari) into SWT;
Netbeans Platform may have some options too.
You may also want to look at Flying Saucer, which is:
An XML/XHTML/CSS 2.1 Renderer
(in 100% Java)
You forgot to set the content type of the JEditorPane.
jep.setContentType("text/html");
What #cletus says is all true. If you want to get your current app going though with a file-based URL, try setting:
URL = "file:///C://print.html"

Categories

Resources