I am trying to implement virtual keyboard using swing. I have made my own design , now If I press on button A it should print A on console. How to do this.? As of now I have done this much...
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
//System.out.println(" "+evt.getSource());
if(evt.getSource()==jButton8)
{
try{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_A);
}
catch(Exception E){}
}
}
Can any one help me in this, and I am doing this in NetBeans IDE.
Although your question is not completely clear to me, the following code might be helpful:
public class VirtualKeyboardRobot {
private Robot robot;
public static void main(final String[] args) {
try {
new VirtualKeyboardRobot().test();
} catch (final AWTException e) {
e.printStackTrace();
}
}
private void test() throws AWTException {
final JFrame frame = new JFrame("Keyboard input to console using robot");
frame.setAlwaysOnTop(true);
frame.setFocusable(false);
frame.setBounds(100, 100, 800, 200);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
robot = new Robot();
robot.setAutoDelay(100);
final ActionListener buttonListener = actionEvent -> {
// See KeyEvent.VK_A: VK_A through VK_Z are the same as ASCII 'A' through 'Z' (0x41 - 0x5A).
final Object source = actionEvent.getSource();
if (source instanceof AbstractButton) {
// Switch from the virtual keyboard to the previous window.
typeKey(KeyEvent.VK_TAB, KeyEvent.ALT_MASK);
// Type the key.
typeKey((int) ((AbstractButton) source).getText().toUpperCase().charAt(0));
}
};
final JPanel keyboardPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
for (char key = 'a'; key <= 'z'; key++) {
final JButton button = new JButton(Character.toString(key));
button.setFocusable(false);
keyboardPanel.add(button);
button.addActionListener(buttonListener);
}
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(keyboardPanel, BorderLayout.NORTH);
final JTextArea textArea = new JTextArea(6, 28);
textArea.setFocusable(false);
frame.getContentPane().add(textArea, BorderLayout.CENTER);
frame.setVisible(true);
}
private void typeKey(final int keyCode, final int mask) {
if ((mask & KeyEvent.ALT_MASK) != 0)
robot.keyPress(KeyEvent.VK_ALT);
typeKey(keyCode);
if ((mask & KeyEvent.ALT_MASK) != 0)
robot.keyRelease(KeyEvent.VK_ALT);
}
private void typeKey(final int keyCode) {
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
}
}
Related
I am creating a basic Java Visual Novel of sorts. It reads a text file and each line in the file is inserted into an ArrayList. By pressing the previous and next buttons, it changes the JTextArea into the next line or previous line.
Now, I want to use a timer so that it does the prev-next thing automatically. How do I go about doing that?
Here is my code:
public class FormativeAss1 {
URL ahaha = getClass().getClassLoader().getResource("ahaha.wav");
URL horror = getClass().getClassLoader().getResource("horror.wav");
URL clash = getClass().getClassLoader().getResource("clash.wav");
URL goriri = getClass().getClassLoader().getResource("goriri.wav");
URL impact = getClass().getClassLoader().getResource("impact.wav");
URL hakushu = getClass().getClassLoader().getResource("hakushu.wav");
JTextArea dialogue_label;
int secondsToWait = 5;
JButton nextButton, prevButton;
Timer tm;
private JFrame frame;
int IntegerQueue = -1;
JLabel Background;
int startedchecker = 0;
public void playSound(URL soundFile) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch (Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
public void IntegerQueueSound(int integer) {
switch (integer){
case 0:
playSound(clash);
break;
case 1:
playSound(horror);
break;
case 2:
playSound(ahaha);
break;
case 3:
playSound(impact);
break;
case 4:
playSound(hakushu);
break;
case 5:
playSound(goriri);
break;
case 6:
playSound(ahaha);
break;
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FormativeAss1 window = new FormativeAss1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FormativeAss1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 944, 595);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.getContentPane().setFocusable(true);
frame.getContentPane().requestFocusInWindow();
JPanel panel = new JPanel();
panel.setBorder(UIManager.getBorder("DesktopIcon.border"));
panel.setBounds(10, 309, 908, 236);
frame.getContentPane().add(panel);
panel.setLayout(null);
dialogue_label = new JTextArea("Press \"Start Dialogue\" to start the novel.");
dialogue_label.setLineWrap(true);
dialogue_label.setWrapStyleWord(true);
dialogue_label.setColumns(1);
dialogue_label.setRows(4);
dialogue_label.setFont(new Font("Yu Gothic UI Semibold", Font.PLAIN, 20));
dialogue_label.setBounds(10, 11, 888, 214);
panel.add(dialogue_label);
JButton StartDialogueButton = new JButton("Start Dialogue");
StartDialogueButton.setBounds(10, 276, 142, 21);
frame.getContentPane().add(StartDialogueButton);
prevButton = new JButton("Previous");
prevButton.setBounds(162, 276, 85, 21);
frame.getContentPane().add(prevButton);
nextButton = new JButton("Next");
nextButton.setBounds(257, 276, 85, 21);
frame.getContentPane().add(nextButton);
JLabel Background = new JLabel("New label");
Background.setBounds(-381, -72, 1257, 1000);
frame.getContentPane().add(Background);
String strLine = "";
ArrayList < String > dialogue_List = new ArrayList < String > ();
ArrayList < String > scenery_List = new ArrayList < String > (Arrays.asList("images/bea.png",
"images/lam.png","images/but.png","images/enj.png","images/ros.png","images/eva.png"
,"images/ber.png", "images/kir.png"));
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Miko\\eclipse-workspace\\Fourth Quarter\\src\\FourthQuarter\\Script.txt"));
while (strLine != null) {
strLine = br.readLine();
if (strLine == null) {
break;
}
dialogue_List.add(strLine);}
br.close();
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
ListIterator<String> it = dialogue_List.listIterator();
frame.getContentPane().setFocusable(true);
frame.getContentPane().requestFocusInWindow();
frame.getContentPane().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(startedchecker==1){
int keyCode = e.getKeyCode();
if(keyCode == 37) {
IntegerQueue = IntegerQueue - 1;
if(IntegerQueue < 0) {
IntegerQueue = 0;
}
} else if(keyCode == 39) {
if (it.hasNext()) {
IntegerQueue = IntegerQueue + 1;}
dialogue_label.setText(dialogue_List.get(IntegerQueue));
Background.setIcon(new ImageIcon (scenery_List.get(IntegerQueue)));
IntegerQueueSound(IntegerQueue);
}
}
}
});
StartDialogueButton.addActionListener(new ActionListener() {
//depending on the IntegerQueue number, certain music or backgrounds will play at different intervals.
public void actionPerformed(ActionEvent arg0) {
startedchecker=1;
}
});
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(startedchecker==1) {
if (it.hasNext()) {
IntegerQueue = IntegerQueue + 1;
dialogue_label.setText(dialogue_List.get(IntegerQueue));
//IntegerQueue = IntegerQueue - 1;
System.out.println(IntegerQueue);
Background.setIcon(new ImageIcon (scenery_List.get(IntegerQueue)));
IntegerQueueSound(IntegerQueue);
}
}
}
});
prevButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg1) {
if(startedchecker==1&&IntegerQueue>0) {
IntegerQueue = IntegerQueue - 1;
dialogue_label.setText(dialogue_List.get(IntegerQueue));
System.out.println(IntegerQueue);
Background.setIcon(new ImageIcon (scenery_List.get(IntegerQueue)));
IntegerQueueSound(IntegerQueue);
}
}
});
}
}
if(keyCode == 37) {
...
} else if(keyCode == 39) {
Don't use "magic numbers". We don't know what a key code of 37 or 39 is. Instead use variable provided by the KeyEvent class like KeyEvent.VK_UP, KeyEvent.VK_DOWN. This makes the code self documenting so we know what keys you are listening for.
I want to use a timer so that it does the prev-next thing automatically
You need to refactor your code.
Your "next" and "previous" listeners need to be refactored into an Action. An Action is essentially the same as your ActionListener since it just implements the actionPerformed(...) method.
The benefit of the Action is that is can now be used by your JButton and by the Swing Timer and by using Key Bindings (which will replace your KeyListener).
Read the Swing tutorial. The following sections will help you solve your problem:
How to Use Actions
How to Use Key Bindings
How to Use Swing Timers
The problem: when you double click on word in JTextArea it is marked, but when you don't release the mouse button and try to mark next word, it is not marking whole word, but single characters instead.
It should mark the whole words (not single characters) when moving mouse (on double click). That's literally the default behavior in all programs which I tried, like: Notepad, Firefox, Chrome, Word, even Netbeans, etc.
Same thing with triple click (when holding and moving the mouse should mark the next line, not characters).
Any ideas? I had hard time Googling this, but since it's a very common thing I believe there must be a simple option or at least someone already have a solution.
Sample code:
public class TestJTextArea
{
public static void main(final String[] args)
{
final JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(500, 500));
panel.add(new JTextArea(), BorderLayout.CENTER);
final JFrame frame = new JFrame("Test");
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Maybe you need to create a customized Caret, for example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TestJTextArea2 {
public Component makeUI() {
String text = "The quick brown fox jumps over the lazy dog.";
JTextArea textArea1 = new JTextArea("default\n" + text);
JTextArea textArea2 = new JTextArea("setCaret\n" + text) {
#Override public void updateUI() {
setCaret(null);
super.updateUI();
Caret oldCaret = getCaret();
int blinkRate = oldCaret.getBlinkRate();
Caret caret = new SelectWordCaret();
caret.setBlinkRate(blinkRate);
setCaret(caret);
}
};
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(new JScrollPane(textArea1));
p.add(new JScrollPane(textArea2));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TestJTextArea2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class SelectWordCaret extends DefaultCaret {
private boolean wordSelectingMode = false;
private int p0; // = Math.min(getDot(), getMark());
private int p1; // = Math.max(getDot(), getMark());
#Override public void mousePressed(MouseEvent e) {
super.mousePressed(e);
int nclicks = e.getClickCount();
if (SwingUtilities.isLeftMouseButton(e) && !e.isConsumed() && nclicks == 2) {
p0 = Math.min(getDot(), getMark());
p1 = Math.max(getDot(), getMark());
wordSelectingMode = true;
} else {
wordSelectingMode = false;
}
}
#Override public void mouseDragged(MouseEvent e) {
if (wordSelectingMode && !e.isConsumed() && SwingUtilities.isLeftMouseButton(e)) {
continuouslySelectWords(e);
} else {
super.mouseDragged(e);
}
}
private void continuouslySelectWords(MouseEvent e) {
Position.Bias[] biasRet = new Position.Bias[1];
JTextComponent c = getComponent();
int pos = c.getUI().viewToModel2D(c, e.getPoint(), biasRet);
if(biasRet[0] == null) {
biasRet[0] = Position.Bias.Forward;
}
try {
if (p0 <= pos && pos <= p1) {
setDot(p0);
moveDot(p1, biasRet[0]);
} else if (p1 < pos) {
setDot(p0);
moveDot(Utilities.getWordEnd(c, pos - 1), biasRet[0]);
} else if (p0 > pos) {
setDot(p1);
moveDot(Utilities.getWordStart(c, pos), biasRet[0]);
}
} catch (BadLocationException bl) {
UIManager.getLookAndFeel().provideErrorFeedback(c);
}
}
}
How do I break a while loop if I click on my jframe shutdown? I 'm making a clicker that needs to be stopped at some point, but it'll just continue clicking even tho the exit has been pressed.
public class ClickWindow {
private JFrame frame;
private static Clicker click;
private static long currTime;
private static long totalTime;
private JTextField textField;
private static int textFieldValue = 0;
private static Boolean Bool = true;
/**
* Launch the application.
*/
public static void main(String[] args) throws InterruptedException {
click = new Clicker();
ClickWindow window = new ClickWindow();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ClickWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setBounds(100, 100, 289, 90);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton_1 = new JButton("Press Space");
btnNewButton_1.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Bool = false;
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
if(textFieldValue == 0){
textFieldValue = 250;
}
try {
while (Bool) {
click.click();
textFieldValue = Integer.parseInt(textField.getText());
Thread.sleep(textFieldValue);
}
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
btnNewButton_1.setBounds(10, 25, 110, 23);
frame.getContentPane().add(btnNewButton_1);
textField = new JTextField();
textField.setBounds(127, 25, 141, 23);
frame.getContentPane().add(textField);
textField.setColumns(10);
}
public void windowClosing(WindowEvent event) {
Bool = false;
}
}
Clicker class
public class Clicker{
public static void click() throws AWTException{
Robot bot = new Robot();
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
Edited with the full code.
You should define the defaultCloseOperation for your JFrame:
JFrame myFrame = new JFrame("MyFrame");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If you set the defaultCloseOperation, hitting the close button will trigger a call to System exit:
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
JFrame myFrame = new JFrame("MyFrame");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//...add components here
myFrame.pack();
myFrame.setVisible(true);
}
catch (Exception e)
{
System.exit(-1);
}
}
});
}
If you want to shutdown the entire application you can just do this:
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This will shutdown your application after the Jframe was closed.
You can also call System.exit(0) in your windowClosing method or whenever you want to shutdown your application
instead of adding the keyListener to your JButton try having your JFrame, i.e. ClickWindow implement it. I think this would work.
I keep getting a stack overflow error when I run this short program I made! please help! Right now all it's supposed to do is take the users input and print their position (in X and Y coordinates). I'm not sure what Stack overflow error is or how to fix it.
import java.awt.*;
import javax.swing.*;
public class ExplorerPanel extends JFrame {
ExplorerEvent prog = new ExplorerEvent(this);
JTextArea dataa = new JTextArea(15, 20);
JTextField datain = new JTextField(20);
JButton submit = new JButton("Submit");
JTextField errors = new JTextField(30);
public ExplorerPanel() {
super("Explorer RPG");
setLookAndFeel();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_…
BorderLayout bord = new BorderLayout();
setLayout(bord);
JPanel toppanel = new JPanel();
toppanel.add(dataa);
add(toppanel, BorderLayout.NORTH);
JPanel middlepanel = new JPanel();
middlepanel.add(datain);
middlepanel.add(submit);
add(middlepanel, BorderLayout.CENTER);
JPanel bottompanel = new JPanel();
bottompanel.add(errors);
add(bottompanel, BorderLayout.SOUTH);
dataa.setEditable(false);
errors.setEditable(false);
submit.addActionListener(prog);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLo…
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] args) {
ExplorerPanel frame = new ExplorerPanel();
}
}
public class ExplorerEvent implements ActionListener, Runnable {
ExplorerPanel gui;
Thread playing;
String command;
String gamedata;
ExplorerGame game = new ExplorerGame();
public ExplorerEvent(ExplorerPanel in) {
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Submit")) {
startPlaying();
}
}
void startPlaying() {
playing = new Thread(this);
playing.start();
}
void stopPlaying() {
playing = (null);
}
void clearAllFields() {
gui.dataa.setText("");
}
public void run() {
Thread thisThread = Thread.currentThread();
while (playing == thisThread) {
// Game code
game.Game();
}
}
}
public class ExplorerGame {
ExplorerPanel gui = new ExplorerPanel();
String command;
int x = 1;
int y = 1;
public void Game() {
command = gui.submit.getText().toLowerCase();
if (command.equals("east")) {x--;}
else if (command.equals("south")) {y--;}
else if (command.equals("west")) {x++;}
else if (command.equals("north")) {y++;}
System.out.println(x + y);
}
}
In ExplorerGame, you have declared: -
ExplorerPanel gui = new ExplorerPanel();
then, in ExplorerPanel: -
ExplorerEvent prog = new ExplorerEvent(this);
and then again, in ExplorerEvent: -
ExplorerGame game = new ExplorerGame();
This will fill the Stack with recursive creation of objects.
ExplorerGame -> ExplorerPanel -> ExplorerEvent --+
^ |
|____________________________________________|
You want to solve the Issue?
I'll Suggest you: -
Throw away the code, and re-design your application. Having a cyclic dependency in your application is a big loop hole, showing a very poor design.
I'm using NetBeans 6.1 as my primary IDE, in there I can't run this splash screen example which have given by the Sun (It throws an nullpointerExeption). But I can run this on command line using this arguments.
java -splash:filename.gif SplashDemo
I dont know how to inject command line arguments in NetBeans. Please someone help.
import java.awt.*;
import java.awt.event.*;
public class SplashDemo extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120, 140, 200, 40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading " + comps[(frame / 5) % 3] + "...", 120, 150);
}
public SplashDemo() {
super("SplashScreen demo");
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for (int i = 0; i < 100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
} catch (InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
};
public static void main(String args[]) {
SplashDemo test = new SplashDemo();
}
}
Go to project properties (right click on a project, and choose properties).
Choose "run" item from the Categories list.
There you can setup the arguments, VM options etc.