I use Google Wave, and I want to emulate the ability to send messages before you actually hit the enter key.
Is there a Java equivalent to the C function _getch()?
You could use the JLine library's ConsoleReader.readVirtualKey() method. See http://jline.sourceforge.net/apidocs/jline/ConsoleReader.html#readVirtualKey().
If you don't want to use a 3rd party library, and if you are on Mac OS X or UNIX, you can just take advantage of the same trick that JLine uses to be able to read individual characters: just execute the command "stty -icanon min 1" before running your program, and then System.in will no longer be line buffered and you can get an individual character using System.in.read(). Unfortunately, this trick doesn't work on Windows, so you would need to use a native library to help (or just use JLine).
I found a code, Equivalent function to C's “_getch()
public static void getCh() {
final JFrame frame = new JFrame();
synchronized (frame) {
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
synchronized (frame) {
frame.setVisible(false);
frame.dispose();
frame.notify();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
});
frame.setVisible(true);
try {
frame.wait();
} catch (InterruptedException e1) {
}
}
}
Initially I thought of System.in.read(), but you need to get input without pressing Enter. That requires native console interaction (and console is different under every system).
So answer is "no, there is no direct analogue".
There's no getch equivalent in java. You might as well create a GUI component and bind the keyEvent Listener.
Custom-made method in Java for getch() function of C
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
class getch
{
public static void getCh()
{
final JFrame frame = new JFrame();
synchronized(frame)
{
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
synchronized(frame)
{
frame.setVisible(false);
frame.dispose();
frame.notify();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
});
frame.setVisible(true);
try
{
frame.wait();
}
catch(InterruptedException e1)
{
}
}
}
}
This will Do the trick but i works only from command line . Not from IDE
Console c =System.console();
Reader r = c.reader();
try {
num= r.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
why don't you just create a variable Scanner that don't use it, the program, in anywhere.
pause0 = pause1.nextInt();
:l it seems a lot more easy... Plus you can put a message saying "Press to continue.";
Related
How can I make this ActionListener into a method for a specific JButton?
(im aware its possible to throw it all in an method but yeah..hm.)
myJButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
//do stuff
}
});
thx y'all,
edit: thanks everyone for the quick responses, my explanation wasn't very clear.
I looked into the use of lambdas and it was pretty much what I was thinking of, though the other ways are great to know aswell.
myButton.addActionListener(e -> myButtonMethod());
public void myButtonMethod() {
// code
}
Thank you again, everyone.
I'll try to be more clear and quicker next time.
Again, your question remains unclear. Your code above has a method, one that code can be put into:
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// you can call any code you want here
}
});
Or you could call a method of the outer class from that method:
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
});
// elsewhere
private void button1Method() {
// TODO fill with code
}
Or you could call a method of the inner anonymous class from that code
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
private void button1Method() {
// TODO fill with code
}
});
Or you could use lambdas:
button2.addActionListener(e -> button2Method());
// elsewhere
private void button2Method() {
// TODO fill with code
}
Or you could use a method reference:
button3.addActionListener(this::button3Method);
// elsewhere
private void button3Method(ActionEvent e) {
// TODO fill with code
}
Up to you to try to be clear on what exactly it is you're trying to do and what's preventing you from doing it.
I need to take a screenshot of an area of my screen, to make that i use "Robot" in Java. But if the user place the windows in the area, the windows will be on the screenshot instead of the background.
I tried to solve my problem by placing a :
myframe.setVisible(false);
But when i look the screenshot the windows appear on it. I thought it was because the windows didn't have enough time to disappear or because the render of the screen wasn't updated yet, so i tried different things like using:
repaint();
Or by placing a
try{}finally{}
block to be sure that the actions in the try block have been finished.
But no one of these solution works. These is other ways in my mind but they looks globally bad because they use functions to wait.
So is there a good solution to my problem?
You could use window listener to fire the screen shot when window is closing:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MainFrame extends JFrame implements WindowListener {
public MainFrame() {
super("Test Frame");
JLabel displayMsg = new JLabel(" Close window");
getContentPane().add(displayMsg);
addWindowListener(this);
setSize(400, 300);
setVisible(true);
}
#Override
public void windowClosing(WindowEvent e) {
System.out.println("WindowListener method called: windowClosing.");
//add you screen capture code here
}
//--Not used
#Override
public void windowClosed(WindowEvent e) {
//do nothing
}
#Override
public void windowOpened(WindowEvent e) {
//do nothing
}
#Override
public void windowIconified(WindowEvent e) {
//do nothing
}
#Override
public void windowDeiconified(WindowEvent e) {
//do nothing
}
#Override
public void windowActivated(WindowEvent e) {
//do nothing
}
#Override
public void windowDeactivated(WindowEvent e) {
//do nothing
}
public void windowGainedFocus(WindowEvent e) {
//do nothing
}
public void windowLostFocus(WindowEvent e) {
//do nothing
}
public static void main(String[] args) {
new MainFrame();
}
}
Use SwingUtilities.invokeLater() to take the actual screenshot. Not 100% sure, but I think that myframe.setVisible(false); doesn't become effective till the program flow goes back to the event dispatching loop.
EDIT:
instead of
useRobotToMakeScreenshot();
write
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
useRobotToMakeScreenshot();
}
}
(of course, you have to replace useRobotToMakeScreenshot() with the actual call to the method that does the screenshooting thing)
I have a Graphical User Interface that has a TextField, my code looks as following:
int port = 0;
try{
port = Integer.parseInt(frame.textfieldInput.getText());
}
catch(NumberFormatException npe)
{
System.out.println("Error! parse exception");
}
System.out.println("The Port is " + port); //is 0
I have to assign the value '0' to port, because otherwise the code wont compile, because the variable wouldn't be initialized.
Because the TextField is empty at the beginning of the Program, getText() wont get a value, which is why port stays '0'.
Is there any way to wait for the input before the code continues?
Found a solution, this is how I solved it:
I created a global variable outside of my ActionListener:
public String value = "";
public void createInput() {
buttonInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value = textfieldInput.getText();
}
});
}
named 'value'.
in my public static void main(String[] args) I declared the following:
while(frame.value.equalsIgnoreCase(""))
{
try
{
System.out.println("waiting...");
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println("interrupted");
}
}
I just have to clear the variable 'value' everytime I used it, so it is empty again for future uses.
I tis not the best way to solve it, but it worked for me.
Below code may give you some idea to more efficient way to get value on focus lost.
JFrame frame = new JFrame();
frame.setSize(50, 50);
TextField field = new TextField();
field.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// continue from here
System.out.println(field.getText());
}
#Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
}
});
frame.getContentPane().add(field);
frame.setVisible(true);
i'm making a java application for mac. the application must have the hability of "Auto Hide" equals to "Command+H" shortcut. i'm trying to do it using setVisible(False) in the JFrame. but it doesn't work. how can i do it?
this is may code:
void hide(){
setNormalScreen(); //disable fullscreen mode
//this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setVisible(false);
this.setState(JFrame.ICONIFIED);
}
and this is what i'm getting:
See the below example. You can hide it via Java code using setVisible(false) as you suggested, then appReOpened() event will be called when the user clicks the app in the dock. When this happens, you can just call setVisible(true). This should mimic the Command-H behavior.
See the commented code below also for an uglier solution.
public class Test extends JFrame implements ActionListener, com.apple.eawt.AppReOpenedListener {
public static void main(String[] args) {
Test frame = new Test();
JButton test = new JButton("test");
test.addActionListener(frame);
com.apple.eawt.Application app = com.apple.eawt.Application.getApplication();
app.addAppEventListener(frame);
frame.getContentPane().add(test);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
// try {
// Robot robot = new Robot();
// robot.keyPress(KeyEvent.VK_META);
// robot.keyPress(KeyEvent.VK_H);
// robot.keyRelease(KeyEvent.VK_H);
// robot.keyRelease(KeyEvent.VK_META);
// } catch (AWTException ex) {
// // TODO Auto-generated catch block
// ex.printStackTrace();
// }
}
#Override
public void appReOpened(AppReOpenedEvent arg0) {
setVisible(true);
}
}
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();
}
}