I am writing a java program and it is properly running on Eclipse, there are no errors and the program gives accurate output. However when I compile it using command prompt it gives me 39 errors.
import java.util.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.*;
public class Main extends JFrame{
public static void main (String args [])
{
JFrame frame = new JFrame (); // making a frame in which we will add all the
// components
FrameWork work = new FrameWork ();
frame.setLayout(null);
frame.setBounds (10,10,700,500);
frame.setResizable(false); // making the frame non resizeable so that components are not misplaced
frame.add (work);
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
} // main ends here
} // main class ends here
class FrameWork extends JPanel
{
// panel in which all the components are added
JPanel panel = new JPanel ();
JTextArea jarea = new JTextArea();
JTextField jfield = new JTextField();
// Buttons that can be used to switch between standard IO NIO and NIO2
JButton IO = new JButton ("Standard IO");
JButton NIO = new JButton ("New IO");
JButton NIO2 = new JButton ("New IO2");
JScrollPane scroll = new JScrollPane();
FrameWork ()
{
// setting the lay out null so that componenets can be places at respective postions
add(panel);
setLayout (null);
setBounds (0,0,700,500);
setBackground(Color.white);
add(jarea);
jarea.setBounds(5,85,670,360);
//setting border arround the JText area
jarea.setBorder(BorderFactory.createLineBorder(Color.black));
jarea.add(scroll);
add(jfield);
jfield.setBounds(10,10,650,25);
// adding Standard IO button and Implemnting action listener
add(IO);
IO.setBounds (50,40,150,40);
IO.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent ae)
{
try {
FileReader reader = new FileReader("test.txt");
BufferedReader buff = new BufferedReader(reader);
jarea.read(buff,null);
buff.close();
}
catch (IOException e) {
}
}
#Override
public void mouseEntered(MouseEvent ae) {
}
#Override
public void mouseExited(MouseEvent ae) {
}
#Override
public void mousePressed(MouseEvent ae) {
}
#Override
public void mouseReleased(MouseEvent ae) {
}});
// adding Standard NIO button and Implementing action listener
add(NIO);
NIO.setBounds (250,40,150,40);
NIO.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent ae) {
// some part of this code from java docs
Path file = Paths.get("test.txt");
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =new BufferedReader(new InputStreamReader(in)))
{
String line = null;
while ((line = reader.readLine()) != null) {
jarea.read(reader,null);
}
} catch (IOException x) {
System.err.println(x);
}
}
#Override
public void mouseEntered(MouseEvent ae) {
}
#Override
public void mouseExited(MouseEvent ae) {
}
#Override
public void mousePressed(MouseEvent ae) {
}
#Override
public void mouseReleased(MouseEvent ae) {
}});
// adding Standard NIO2 button and Implemnting action listener
add(NIO2);
NIO2.setBounds (450,40,150,40);
NIO2.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent ae) {
try
{
ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
Path file = Paths.get("test.txt");
ReadableByteChannel rbc = Files.newByteChannel(file);
int counter =0;
int flag = 0;
int enter = 0;
while(counter != -1)
{
buffer.rewind ();
counter = rbc.read(buffer);
buffer.rewind();
flag++;
for(enter =0 ; enter <= counter-1 ; enter++)
{
byte by = buffer.get();
jarea.append(""+(char)by);
}
}
}
catch(Exception e){}
}
#Override
public void mouseEntered(MouseEvent ae) {
}
#Override
public void mouseExited(MouseEvent ae) {
}
#Override
public void mousePressed(MouseEvent ae) {
}
#Override
public void mouseReleased(MouseEvent ae) {
}});
} // constructor ends
} //FrameWork Class ends
Errors:
Edit: based on the images of errors that you uploaded later, it looks like you are using a Java 1.6 or earlier compiler. Do java -version to see what version you are using.
Update your windows path to use the java 1.7 version that you have elsewhere on your machine.
In Command Line - Remove the imported packages on top , when it is a single file and standalone application.
Check List:-
Make user the libraries are available to the existing location.
Set the class path perfectly.
Execute the below commands to ensure they environmental variables are set properly for jdk and jre
c:\javac
c:\java
I ran into a similar issue today. My program was working fine in the Eclipse debugger but misbehaving from the OS command line. It finally turned out to be a CLASSPATH issue. My code was incompatible with a JAR that I had included in my CLASSPATH environment variable for the OS shell. This JAR was not even required for my program. For Eclipse I had only linked the requisite JARs, so this problem did not manifest in the Eclipse debugger. After excluding the offending JAR from my CLASSPATH, the problem disappeared.
Related
I want to write a live search using Swing components. I am using a keyListener to keep track of the input. Basically i dont want the keyListener to take action every time a button is pressed but instead wait (for some period of time) for more incoming input. This period of time is refreshed every time a button is pressed and the input gets evaluated when it eventually times out (e.g. no button is being pressed within the period meaning that the input is complete). How do I implement that into my keyListener?
Code snippet of main method:
static JTextField nameTextField = new JTextField();
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(nameTextField, BorderLayout.NORTH);
nameTextField.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent keyEvent) {
//
}
#Override
public void keyPressed(KeyEvent e) {
//
}
#Override
public void keyReleased(KeyEvent e) {
if(waitForMoreInput(50)) {
doSomething(nameTextField.getText());
}
}
}
}
}
);
frame.setSize(250, 100);
frame.setVisible(true);
}
Thanks in advance
Much better is for you to use a DocumentListener or DocumentFilter, depending on if you want to listen before or after text has been fully registered with the text component.
The DocumentListener will register any time the text has changed, be it via a key press, via a copy and paste, via a deletion of text. The Timer will then wait however long you wish to do whatever action is required on the text. For example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class DocListenerFoo extends JPanel {
private JTextField nameTextField = new JTextField(20);
public DocListenerFoo() {
add(new JLabel("Add Text:"));
add(nameTextField);
int timerDelay = 1000; // one second
nameTextField.getDocument().addDocumentListener(new MyDocListener(timerDelay));
}
private class MyDocListener implements DocumentListener {
private Timer docTimer;
private int timerDelay;
public MyDocListener(int timerDelay) {
this.timerDelay = timerDelay;
}
#Override
public void changedUpdate(DocumentEvent e) {
textChangedAction(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
textChangedAction(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
textChangedAction(e);
}
private void textChangedAction(DocumentEvent e) {
Document doc = e.getDocument();
try {
String text = doc.getText(0, doc.getLength());
if (docTimer != null && docTimer.isRunning()) {
docTimer.stop();
}
docTimer = new Timer(timerDelay, new TimerListener(text));
docTimer.setRepeats(false);
docTimer.start();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
private class TimerListener implements ActionListener {
private String text;
public TimerListener(String text) {
this.text = text;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO do check on text here
System.out.println("Checking text here: " + text);
}
}
private static void createAndShowGui() {
DocListenerFoo mainPanel = new DocListenerFoo();
JFrame frame = new JFrame("DocListenerFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Don't wait inside the key or document event, it just blocks the program from being processed further. Instead save the current time or (re)start a timer in the event and execute your action later somewhere else.
I'm guessing that you're trying to use a KeyListener with a Swing text component such as a JTextField (I have to guess since you don't tell or show us). If so, then the best solution is don't. Using a KeyListener with these components can mess up the functionality of the components. Much better is for you to use a DocumentListener or DocumentFilter, depending on if you want to listen before or after text has been fully registered with the text component.
For a better more complete answer, post a better more complete question, including your minimal code example and details about your problem.
In my online Java class, I need to write a program that counts the number of mouse clicks on a button within a frame. Here is my code:
import java.awt.*;
import java.awt.event.*;
public class option1 extends Frame {
option1() {
setTitle("Final Project Option 1");
setSize(300,300);
show();
}
public static void main(String[] args) {
option1 test = new option1();
int a = 0;
String s1 = "" + a;
Frame objFrame;
Button objButton1;
Label objLabel1;
objFrame = new option1();
objButton1 = new Button("Button");
objLabel1 = new Label();
objLabel1.setBounds(150,220,50,30);
objButton1.setBounds(40,35,50,50);
objLabel1.setText(s1);
objButton1.addMouseListener(new MyMouseListener()); //line 29
objFrame.add(objLabel1);
objFrame.add(objButton1);
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
a++; //line 36
}
}
}
When compiling, I get two errors. One error is on line 29, which is "non-static variable this cannot be referenced from a static context", and the other is on line 36, which is "cannot find symbol".
So, what exactly am I doing wrong? I would appreciate responders telling exactly what I need to do to fix the problem, and avoiding using technical terms since I'm rather new to programming.
I see two issues, namely your inner class should be static (to use it without an instance of option1 which should probably be Option1 to fit with Java naming conventions) and you need to define and initialize a. Something like
public static class MyMouseListener extends MouseAdapter {
int a = 0; //<-- add this.
public void mouseClicked(MouseEvent me) {
a++;
}
}
Also, I suggest you consider using the more modern JFrame instead of the older Frame.
Edit
You'll need to save a reference to your MouseListener like
MyMouseListener mml = new MyMouseListener();
objButton1.addMouseListener(mml);
Then you can get it the a like
System.out.println(mml.a);
Finally, your original approach of "" + a would be "0".
Generally, as soon as you possibly can, get out of the main method into a non-static context...
public class option1 extends Frame {
private int a = 0;
private Label objLabel1;
option1() {
setTitle("Final Project Option 1");
setSize(300,300);
Button objButton1;
objButton1 = new Button("Button");
objLabel1 = new Label();
objLabel1.setBounds(150,220,50,30);
objButton1.setBounds(40,35,50,50);
objLabel1.setText(Integer.toString(a));
objButton1.addMouseListener(new MyMouseListener()); //line 29
add(objLabel1);
add(objButton1);
show();
}
public static void main(String[] args) {
option1 test = new option1();
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
a++; //line 36
objLabel1.setText(Integer.toString(a));
}
}
}
Generally speaking, AWT is out-of-date (by some 15 years) and you really should be trying to use Swing or JavaFX instead.
Buttons should use ActionListener, as a mouse is not the only way a button might be triggered
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
I just tried to make your code working. But there is some issues regarding the standard Java coding. But you should consider previous answers concerning the coding style.
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class Main {
public static void main(String[] args) {
final Frame mainFrame = new OptionOne();
Button button = new Button("Button");
final Label label = new Label();
label.setBounds(150, 220, 50, 30);
label.setText("0");
button.setBounds(40, 35, 50, 50);
label.addPropertyChangeListener(label.getText(), new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
mainFrame.addNotify();
}
});
button.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
int value = Integer.parseInt(label.getText());
label.setText(String.valueOf(value + 1));
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
mainFrame.add(label);
mainFrame.add(button);
}
}
class OptionOne extends Frame {
OptionOne() {
setTitle("Final Project Option 1");
setSize(300, 300);
show();
}
}
Hi take a look on this fragment of code. My aim is to make my app reacting when i will type in a textarea one of words listed in slowa[]. As u can see i created inputMethodListner however when i type whatever word it is working at all. i tryied to put a debug prints to see what is going on and i see that neither method inputMethodTextChanged() nor inputMethodTextChanged() is called even once:( what im doing wrong?
import java.awt.*;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import javax.swing.*;
public class BrzydkieSlowa extends JFrame {
static String[] slowa = {"shit", "fuck"};
private BrzydkieSlowa(){
//Create and set up the window.
JFrame frame = new JFrame("Brzydkie slowa");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextArea textArea1 = new JTextArea(10,10);
textArea1.addInputMethodListener(new InputMethodListener() {
#Override
public void caretPositionChanged(InputMethodEvent arg0) {
int brzydkie = 0;
int i = 0;
while(brzydkie == 1 || i > 1){
if(textArea1.getText().compareTo(slowa[i])== 0)
brzydkie = 0;
i++;
}
if(brzydkie == 1)
JOptionPane.showMessageDialog(null, "brzydkie slowo");
}
#Override
public void inputMethodTextChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
});
frame.getContentPane().add(textArea1, BorderLayout.CENTER);
//Display the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new BrzydkieSlowa();
}
}
You should use DocumentListener instead.
Try
textArea1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
String text = textArea1.getText();
int firstOccurence = StringUtils.indexOfAny(text, slowa);
if (firstOccurence > -1) {
/* do something */
}
}
#Override
public void removeUpdate(DocumentEvent e) {/* do nothing */ }
#Override
public void changedUpdate(DocumentEvent e) { /* do nothing */ }
});
Please notify that How to "Write a Document Listener" warns against modifying text:
Document listeners should not modify the contents of the document; The change is already complete by the time the listener is notified of the change. Instead, write a custom document that overrides the insertString() or remove() methods, or both.
There are some examples for a Document model which might help you. They included approaches for filter and undo changes.
I added one MouseMotionListener to the JTextField. But when I use jf.getMouseMotionListeners().length to know about how many mouse listeners are registered then I get 3!!. That's causing me some problem because I'm trying to add a listener depending on that length. If its zero I add or else I don't want to add a listener.
Below is the code and I have written code to know the length in mouse moved event.
public static void main(String args[]) {
JFrame fr = new JFrame();
final JTextPane jf = new JTextPane ();
jf.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent arg0) {
System.out.println(jf.getMouseListeners().length);
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
jf.setBounds(30,30,100,50);
fr.setSize(new Dimension(500, 500));
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLayout(null);
fr.add(jf);
fr.setVisible(true);
}
Why is that length 3 when I added just one listener?
is there a better way to check whether a listener on a component is registered or not?
EDIT
Here's what I'm trying to do.
I should be able to drag the JTextPane any where inside window and I should be able to edit it by double clicking on the JTextPane .
If I have a drag listener while editing and If wan't to select a text to style it the JTextPane gets dragged instead of selecting a text from JTextPane.
Now I want to remove the motionlistener when I am in editing mode and add it when I'm not editing.
So thats why I'm trying to remove it or in simple I need to disable the motionlistener.
output is correct, JTextField has another notifiers implemented API, they are notified from added MouseListener
see whats debuger returns
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MouseAndJTextField {
private JFrame fr = new JFrame();
private JTextField jf = new JTextField(20);
public MouseAndJTextField() {
jf.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println(jf.getMouseListeners().length);
}
});
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.add(jf);
fr.pack();
fr.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MouseAndJTextField fs = new MouseAndJTextField();
}
});
}
}
You can define your class (inner class) instead of the Anonymous inner class for the listener and go through the listeners calling instanceof to find whether your instance is added.
Alternatively you can define a flag indicating whether the listener should process event or not. Set the flag by default to true. Set to false when you have to skip event (in your edit mode) and reset after.
I have a text area that I would like to become blank when the enter button is pressed. I know this would normally be done with a setText method. However when I do this, the text is removed but the new line function created by the return key being pressed. My question is, is the anyway of stopping this default action from happening?
thanks
Are you listening for the ENTER key on the text area and then clearing it? The following works for me:
final JTextArea ta = new JTextArea();
ta.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
ta.setText("");
}
}
#Override
public void keyPressed(KeyEvent e) {
}
});
Hi
I have a text area that I would like to become blank when the enter button is pressed.
This, I understand. Here's how you can do that:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
public static void main(String[]args) {
final JFrame frame = new JFrame();
final JTextArea area = new JTextArea();
area.setPreferredSize(new Dimension(200, 200));
area.addKeyListener(new KeyAdapter(){
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
area.setText("");
}
}
});
frame.add(area);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
I know this would normally be done with a setText method. However when I do this, the text is removed but the new line function created by the return key being pressed. My question is, is the anyway of stopping this default action from happening?
That, I don't understand.
The problem is probably that you are not consuming the keystroke event, and although the text area is cleared, the normal processing of the keystroke ends up inserting a newline.
Rather than trapping the keystroke event (which isn't necessarily portable) I would recommend using a DocumentFilter. There is a tutorial here that shows you how to write one. Implement the filter so that when there is a 'newline' in the insert or replace string, replace the entire contents of the document with "".
However this approach can't tell the difference between a newline typed at the keyboard and one pasted into the text area.
Before you clear the text you need to remove the new line code the return button left. You do that with the consume() method.
So to clear your text:
yourkeyevent.consume();
yourTextObject.setText("");
Instead, you can also use:
yourTextarea.setText(null);
yourTextarea.setCaretPosition(-1);
I solved your problem overriding the code in the method "public void keyTyped(KeyEvent e)" instead of "public void keyPressed(KeyEvent e)" and it works.
Here the code:
package versione1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WhiteEnter {
final JFrame frame = new JFrame();
private JTextArea area = new JTextArea();
public static void main(String[]args) {
WhiteEnter prova = new WhiteEnter();
prova.run();
}
public void run(){
area.setPreferredSize(new Dimension(200, 200));
area.addKeyListener(new PressEnterKeyListener());
frame.add(area);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public class PressEnterKeyListener implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == (KeyEvent.VK_ENTER)){
try{
area.setText(null);
area.setCaretPosition(0);
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}