So, I'm fairly new to programming and I like to fiddle with it and one day my friend asked me to make a program where when you click, "ctrl" and "s" would be "pressed". I looked at lots of forums trying to make a functional code but, since I'm new to Java, I only got separate pieces of codes and threw it all together.
My code looks like this:
import java.awt.event.MouseEvent;
import java.awt.*;
import java.awt.event.*;
import java.awt.Robot;
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("press any key to exit.");
keyboard.next();
System.exit(0);
}
public void mouseClicked(MouseEvent evt) {
try {
Robot robot = new Robot();
// Simulate a key press
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (AWTException e) {
}
}
}
Your program has no GUI and, therefore, nothing to invoke your mouse listener. The code within the listener appears correct, all you need to do is search for how to create a basic GUI and add the mouse listener to it so you get the results you want.
The following code may help you to handle Ctrl + S
public class SwingApp1 extends JFrame implements KeyListener {
public SwingApp1() {
setSize(500, 500);
setLocationRelativeTo(null);
setBackground(Color.blue);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingApp1 main = new SwingApp1();
main.setVisible(true);
}
#Override
public void keyTyped(KeyEvent evt) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Pressed=>" + e.getKeyCode());
if (e.getKeyCode() == 83) {
System.out.println("Pressed Ctrl + S");
} // Ctrl + S
}
#Override
public void keyReleased(KeyEvent e) {
}}
Related
I've got a problem with my program what I can't solve. I'm trying for hours and tried to google, etc... I've seen many programs, which is working, but I don't know why my solution does not. My goal (for now) is simple, I want to write to the cmd-line in case of a mouse click or a key press. The first one works, but the second is not. Can anyone tell my why?
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class test {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public test() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("Mouse has clicked!");
}
});
frame.getContentPane().addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println("A key has pressed.");
}
});
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Well, finally I had enough time trying to find the solution and now I'm discovered it. I do not know why, but it was not possible to add a keyListener to the JFrame. I could only add for a JButton or a JTextField, etc... This is strange for me, a little bit :c
I know there was milions of questions about that, but I can't understand most of them. I've seen that people make something like that:
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()== KeyEvent.VK_Q)
//do something
}
but keyPressed must override methos of some class to work or be runned in other thread. I really don't know how to do that. Can someone give me code of the easiest keylistener for java.
It should work even when program is not focused (it's just console program).
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.*;
import javax.swing.JFrame;
public class SquatCounter {
class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()== KeyEvent.VK_Q)
System.out.println("Key Q pressed!");
}
}
JFrame jf = new JFrame("title");
public SquatCounter() {
jf.addKeyListener(new MyKeyListener());
}
public static void main(String[] args) {
Key1 key = new Key1 ();
SquatCounter test = new SquatCounter();
}
}
When you setup the JFrame, add a KeyListener like this:
JFrame jf = new JFrame("title");
jf.addKeyListener(new MyKeyListener());
jf.setVisible(false);
(The jf.setVisible(false); stops the program window from appearing (only command line)
Then create a new class called MyKeyListener that extends KeyAdapter.
class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode()== KeyEvent.VK_Q)
System.out.println("Key Q pressed!");
}
}
Now let me explain things a bit.
First, when you create a JFrame, it has no default KeyListener attached. Therefore, we have to create a class MyKeyListener to do that.
Secondly, we extended KeyAdapter instead of implementing KeyListener because there are a lot more methods than what you need in there. You only need to override the keypressed() method when you extends KeyAdapter but you have to implement all (I think it's 3) the other methods that you don't need for your purposes.
Lastly, if you want to do other methods like keyreleased(), just add it in to the MyKeylistener class and it will work.
Hope this helps!
EDIT: Per OP's request, it should be like this:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (line.equalsIgnoreCase("q") == false) {
line = in.read();
System.out.println("Q is pressed!");
}
in.close();
Just add a KeyListener.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.*;
import javax.swing.JFrame;
public class SquatCounter {
JFrame jf = new JFrame("title") {{
setVisible(true);
setDefaultCloseOperation(3); // EXIT_ON_CLOSE
}};
public SquatCounter() {
jf.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent event) {
if (e.getKeyCode()== KeyEvent.VK_Q)
//do something
}
#Override
public void keyReleased(KeyEvent event) {
// different stuff
}
#Override
public void keyTyped(KeyEvent event) {
// more stuff
}
});
}
public static void main(String[] args) {
SquatCounter test = new SquatCounter();
}
}
Doing something out of focus has an answer here: Stackoverflow: Listening for input without focus in Java
Hello I'm currently working in my java file.
I'd like to add an event on JFormattedTextField when I press the enter key.
This is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.text.ParseException;
public class Test extends JFrame implements ActionListener
{
JFormattedTextField phoneField;
Test()
{
setTitle("JFormatted Text");
setLayout(null);
MaskFormatter mask = null;
try {
mask = new MaskFormatter("##########");
} catch (ParseException e) {
e.printStackTrace();
}
phoneField = new JFormattedTextField(mask);
phoneField.setBounds(20, 20, 150, 30);
phoneField.addActionListener(this);
setVisible(true);
setSize(200, 200);
getContentPane().add(phoneField);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== phoneField)
{
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
}
it works but their the user needs to enter 10 digits.
Add an ActionListener to the field. It is better than using the (low level) KeyListener and will conform to whatever that OS accepts as 'end of entry'.
Don't use KeyListener instead use DocumentListener.
It has the following methods which captures the changes in the JTextField
JTextField textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent arg0) {
// Gives notification that a portion of the document has been removed.
}
#Override
public void insertUpdate(DocumentEvent arg0) {
// Gives notification that there was an insert into the document.
}
#Override
public void changedUpdate(DocumentEvent arg0) {
// Gives notification that an attribute or set of attributes changed.
}
});
You could add a keyListener instead.
phonefield.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == evt.VK_ENTER){
System.out.println("The numbers you enter are "+phoneField.getText());
}
}
});
If this isn't your problem, you should expand a little and clarify.
EDIT:
As comments and other answers pointed out, you should go for an ActionListener instead. Reasoning can be found below.
What I want to do is the moment I pressed the keyboard, whatever is written on the textfield will be shown in the System.out.printLn(). but for every type I make, it will only be shown if I pressed another key.
for example.. I press 'A' ...then a blank space will be shown.
I press 'B' ...then 'A' will be shown.
I press 'C' ...then 'AB' will be shown.
what I want is if I press 'A' ...then 'A' will be shown...etc
is it possible? I also tried this on keyTyped() but the result is just the same..
here is my short code for this...
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class NewClass extends JFrame implements KeyListener{
JTextField tf = new JTextField();
NewClass(){
this.setLayout(null);
tf.setBounds(50, 50, 200, 30);
add(tf);
tf.addKeyListener(this);
}
public static void main(String[] args) {
NewClass r = new NewClass();
r.setVisible(true);
r.setSize(300, 200);
r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println(tf.getText());
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Any suggestions? thanks in advance :)
The problem is that keyPressed is being called before the TextBox is updated.
Instead of
tf.addKeyListener(this);
Try using this:
tf.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
printIt();
}
public void removeUpdate(DocumentEvent e) {
printIt();
}
public void insertUpdate(DocumentEvent e) {
printIt();
}
public void printIt() {
System.out.println(tf.getText());
}
You'll need to import javax.swing.event.DocumentEvent and javax.swing.event.DocumentListener.
I've been trying and failing to use the java full screen mode on the primary display of an OSX system. Whatever I've tried I can't seem to get rid of the 'apple' menu bar from the top of the display. I really need to paint over the entire screen. Can anyone tell me how to get rid of the menu?
I've attached an example class which exhibits the problem - on my system the menu is still visible where I would expect to see a completely blank screen.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class FullScreenFrame extends JFrame implements KeyListener {
public FullScreenFrame () {
addKeyListener(this);
setUndecorated(true);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
try {
gd.setFullScreenWindow(this);
}
finally {
gd.setFullScreenWindow(null);
}
}
else {
System.err.println("Full screen not supported");
}
setVisible(true);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
setVisible(false);
dispose();
}
public static void main (String [] args) {
new FullScreenFrame();
}
}
I think your problem is here:
try {
gd.setFullScreenWindow(this);
}
finally {
gd.setFullScreenWindow(null);
}
finally blocks are always executed, so what happens here is that you window becomes full screen for a brief instant (if that) and then relinquishes the screen immediately.
Also, setVisible(true) is not necessary when you have previously called setFullScreenWindow(this), according to the Javadocs.
So I would change the constructor to this:
public FullScreenFrame() {
addKeyListener(this);
GraphicsDevice gd =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
setUndecorated(true);
gd.setFullScreenWindow(this);
} else {
System.err.println("Full screen not supported");
setSize(100, 100); // just something to let you see the window
setVisible(true);
}
}
On OS X (10.7 and higher), it is better to use the native fullscreen mode available. You should use:
com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(window,true);
com.apple.eawt.Application.getApplication().requestToggleFullScreen(window);
where window is the window (JFrame, etc) that you want to take fullscreen
Thats a bit pedantic, the answer is to follow the tutorial completely, which has the essentials and is somewhat more expansive than would fit in a post. The above sample does not work because it is missing a validate(); and some content. I suspect the Java Tutorial will not disappear any time soon. Below is a modified version
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FullScreenFrame extends JFrame implements KeyListener {
public FullScreenFrame () {
addKeyListener(this);
setUndecorated(true);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
try {
this.getContentPane().addKeyListener(this);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add("Center", new JLabel("Full Screen, back to normal in 10 seconds"));
gd.setFullScreenWindow(this);
validate();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
gd.setFullScreenWindow(null);
}
} else {
System.err.println("Full screen not supported");
}
}
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped:" + e.getKeyChar() + "source:" + e.getSource() );
}
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed:" + e.getKeyChar() + "source:" + e.getSource() );
}
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased:" + e.getKeyChar() + "source:" + e.getSource() );
setVisible(false);
dispose();
}
public static void main (String [] args) {
new FullScreenFrame();
}
}