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.
Related
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" );
I have created the following code for a school project, a "password protector", just for fun, really. However, the problem I have is that the icon image does not appear, but instead the default java "coffee cup".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserInterfaceGUI extends JFrame
{
private static final long serialVersionUID = 1;
private JLabel userNameInfo; // ... more unimportant vars.
public UserInterfaceGUI()
{
this.setLayout(new FlowLayout());
userNameInfo = new JLabel("Enter Username:"); // ... more unimportant var. declartions
this.add(userNameInfo); // ... more unimportant ".add"s
event e = new event();
submit.addActionListener(e);
}
public static void main(String[] args)
{
//This icon has a problem \/
ImageIcon img = new ImageIcon("[File Location hidden for privacy]/icon.ico");
UserInterfaceGUI gui = new UserInterfaceGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(400, 140);
gui.setIconImage(img.getImage());
gui.setTitle("Password Protector");
gui.setVisible(true);
}
}
Can someone tell me why this just shows the java coffee cup at the bottom of the screen and on the bar at the top of the window?
There are two likely problems here:
Java is unlikely to support .ico files. The only types that can be relied on are GIF, PNG & JPEG. For all types supported on any specific JRE, use ImageIO.getReaderFileSuffixes() (but seriously, for app. icons stick to the 3 types with guaranteed support).
The code is trying to load an application resource as a file, when it will likely be (or become) an embedded-resource that should be accessed by URL. See the embedded resource info. page for tips on how to form the URL.
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.
I am trying to get this code work (applet) its based on webrenderer trial , I got this code in example section.
Though I tried searching there site but it was of no use.I want to render page on my applet .
Below is full code I used , I really don't know what is wrong there.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.webrenderer.swing.*;
/**
* This example shows how to set up WebRenderer to run Java Applets
*
* #author JadeLiquid Software.
* #see www.webrenderer.com
*/
public class AppletExample
{
// instance of a browser
IMozillaBrowserCanvas browser;
JTextField textfield;
public AppletExample()
{
// Creates a JFrame to host the browser
JFrame frame = new JFrame("Applet Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and append the browser
frame.setContentPane(createContent());
frame.setSize(640, 480);
frame.setVisible(true);
}
public JPanel createContent()
{
JPanel panel = new JPanel(new BorderLayout());
textfield = new JTextField();
panel.add(BorderLayout.NORTH, textfield);
// The action listener triggers when text is entered in the text field
textfield.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
browser.loadURL(textfield.getText());
}
});
// If you are behind a proxy server, it may be necessary to set the proxy authentication
// to enable access for page loading. Enable the following call(s) with the appropriate
// values for domain, port..
// These settings will need to be applied to both the browser and to enable applets.
//int yourProxyPort = 8080;
//String yourProxyServer = "proxyserver";
// Apply proxy settings to enable applets. Username and password will need to entered as
// a dialog does not appear automatically as is the case with the browser proxy.
//BrowserFactory.setAppletProxySettings(yourProxyServer, String.valueOf(yourProxyPort));
//BrowserFactory.setAppletProxyAuthentication("username", "password");
// Create a browser instance
browser = BrowserFactory.spawnMozilla();
// Required if a proxy server is being used.
//browser.setProxyProtocol(new ProxySetting( ProxySetting.PROTOCOL_ALL, yourProxyServer, yourProxyPort));
//browser.enableProxy();
// Required call to allow applets to function
browser.setAppletMode(IMozillaBrowserCanvas.ENABLE_JAVA_APPLETS);
// Load a site with many applet examples
browser.loadURL("java.sun.com/applets/jdk/1.4/index.html");
// Attach to the panel
panel.add(BorderLayout.CENTER, browser.getComponent());
return panel;
}
public static void main(String[] args)
{
/*
* TODO: Insert your username and key in the following setLicenseData call.
* WebRenderer operates with reduced functionality if the username and key are not correct.
* The sample key used below is a limited-duration trial key.
*/
BrowserFactory.setLicenseData( "30dtrial" , "9Q2QFT9JIK4OHO5BSNKHNMM9EMTR5NRG" );
new AppletExample();
}
}
When i try to run it i get error
java.lang.reflect.InvocationTargetException
Here is debug info
Initializing jdb ...
Internal exception:
java.io.IOException: The handle is invalid
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:242)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:273)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at com.sun.tools.example.debug.tty.TTY.<init>(TTY.java:751)
at com.sun.tools.example.debug.tty.TTY.main(TTY.java:1067)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.applet.Main.invokeDebugger(Main.java:314)
at sun.applet.Main.run(Main.java:143)
at sun.applet.Main.main(Main.java:98)
Please make sure that you have followed these steps as outlined in the documentation: http://www.webrenderer.com/products/swing/developer/developersguide/files/appletdeploy.htm
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();