public final class UserPage extends JFrame{
public UserPage() {
this.addKeyListener(new myclass());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setLocation(300, 60);
this.setResizable(false);
this.setVisible(true);
}
.
.
.
public class myclass extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
System.out.println("Key \"Delete\" Pressed");
}
}
}
}
But, when i press delete button, not see the "Key \"Delete\" Pressed" message!
JFrame (all Top-Level Containers) by default never to react to KeyEvents, have to use this Listener for JComponent they are to consume Focus, or is possible to flag it with setFocusable()
don't to use low_level KeyListener for Swing JComponents, if is possible then to use hight level abstraction, to use KeyBindings instead
JRootPane + KeyBindings(As #mKorbel has already said)
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
Also check out: JMenuItem#setAccelerator(...)
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UserPageTest {
public static JMenuBar makeMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Test");
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
menu.add(item);
bar.add(menu);
return bar;
}
public static Action action = new AbstractAction("UserPage?") {
#Override public void actionPerformed(ActionEvent e) {
System.out.println("UserPage Action");
}
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setJMenuBar(makeMenuBar());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Related
I would like to perform some action when 'Enter' key is press as soon as jbutton is clicked but it is not working, someone help
here is my code
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jButton.keyTyped(e);
}
key listener function
public void keyTyped(KeyEvent e) {
//action
}
You need to bind it - sample code below.
public class Test {
static JButton btnA = new JButton("A");
static JPanel jp = new JPanel();
static JFrame jf = new JFrame("test frame");
static ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
jl.setText(((JButton)e.getSource()).getText());
}
};
public static void main(String[] args) {
jf.setVisible(true);
jf.setSize(400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp.add(btnA);
jf.add(jp);
btnA.addActionListener(action);
}
}
So I wanted to make a program that holds down the mouse button for me.
So far I've got this: http://pastebin.com/UTJwdHY7
What I'm wondering is how I can stop it. Also, what I realise is that stopping the button makes no sense as I wouldn't be able to click it anyway. Also some tips on how I've done so far would be nice.
Edit (Adding code):
package main;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.beans.PropertyChangeListener;
public class clickForever extends JFrame implements ActionListener {
public static boolean isClicking = false;
public void actionPerformed(ActionEvent e) {}
public void createFrame() { initComponents(); }
public void initComponents() {
JFrame frame = new JFrame("AutoClicker");
JPanel panel = new JPanel(true);
JButton button = new JButton("OKAY");
JLabel label = new JLabel();
frame.setVisible(true);
frame.setSize(350, 67);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.add(panel);
button.addActionListener(new Action() {
#Override
public Object getValue(String s) {
return null;
}
#Override
public void putValue(String s, Object o) {}
#Override
public void setEnabled(boolean b) {}
#Override
public boolean isEnabled() {
return false;
}
#Override
public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) {}
#Override
public void removePropertyChangeListener(PropertyChangeListener propertyChangeListener) {}
#Override
public void actionPerformed(ActionEvent actionEvent) {
if(isClicking){isClicking = false; return;}
if(!isClicking){isClicking = true; return;}
}
});
label.setFont(new Font("Times New Roman", 1, 16));
label.setText("Click 'OKAY' to start.");
label.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(label);
panel.setBorder(new LineBorder(Color.BLACK));
panel.add(button);
}
public static void main(String[] args) throws java.awt.AWTException, java.lang.InterruptedException {
clickForever clickForever = new clickForever();
Robot rbt = new Robot();
clickForever.createFrame();
while(true){
if(isClicking) rbt.mousePress(InputEvent.BUTTON1_MASK);
if(!isClicking) ;
}
}
}
Add a key listener to the frame, and when the key is pressed, stop the pressing. Note that this will not work if the frame goes out of focus, in which case you would have to listen for a global key press, which I believe would be much more difficult.
You Can Use This To End Your Program And Try Link It To The Press Of A button
Code:
public class Main {
public static void main(String[] args) {
System.out.println("Statement 1");
System.exit(0);
System.out.println("Statement 2");
}
}
When I press tab key on the keyboard I want to select my text fields in above order.how to do that?
Try this example....
package com.Demo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
#SuppressWarnings("serial")
public class TabTest extends JFrame {
public TabTest() {
initialize();
}
private void initialize() {
setSize(300, 300);
setTitle("JTextArea TAB DEMO");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JTextField textField = new JTextField();
JPasswordField passwordField = new JPasswordField();
final JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
//
// Add key listener to change the TAB behaviour in
// JTextArea to transfer focus to other component forward
// or backward.
//
textArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_TAB) {
if (e.getModifiers() > 0) {
textArea.transferFocusBackward();
} else {
textArea.transferFocus();
}
e.consume();
}
}
});
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(passwordField, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TabTest().setVisible(true);
}
});
}
}
jTextField1.setNextFocusableComponent(jTextField2);
jTextField2.setNextFocusableComponent(jTextField3);
jTextField3.setNextFocusableComponent(jTextField4);
jTextField4.setNextFocusableComponent(jTextField5);
try this :)
Try this:
txtfld.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfld.setText("aaa");
}
#Override
public void focusLost(FocusEvent e) {
...
}
});
see more complete code.
I am making a word processor application in order to practise Java and I would like it so that when the user attempts to close the appliction, a JFrame will come up asking to save changes.
I was thinking about setDefaultCloseOperation() but I have had little luck so far. I would also like it to appear whent he user clicks the "X" on the top right of the window aswell if possible.
You can set the JFrame DefaultCloseOperation to something like DO_NOTHING, and then, set a WindowsListener to grab the close event and do what you want. I'll post an exemple in a few minutes .
EDIT: Here's the example :
public static void main(String[] args) {
final JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(800, 600);
frame.addWindowListener(new WindowAdapter() {
//I skipped unused callbacks for readability
#Override
public void windowClosing(WindowEvent e) {
if(JOptionPane.showConfirmDialog(frame, "Are you sure ?") == JOptionPane.OK_OPTION){
frame.setVisible(false);
frame.dispose();
}
}
});
frame.setVisible(true);
}
import java.awt.event.*;
import javax.swing.*;
public class QuickGuiTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
final JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(600, 400);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(
frame, "Are you sure?");
if( result==JOptionPane.OK_OPTION){
// NOW we change it to dispose on close..
frame.setDefaultCloseOperation(
JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(false);
frame.dispose();
}
}
});
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
You have to add a WindowListener to the JFrame.
Inside the windowClosing method, you can provide required code.
For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private JFrame frame = new JFrame();
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
};
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
}
});
}
}
I have a JDesktopPane and a JInternalFrame. I'd like the JInternalFrame to automatically maximize after I make it. How can I hardcode the "maximize window" event?
Use JInternalFrame.setMaximum(true) after you create your frame.
Here is how you can maximize your frame:
JInternalFrame frame = ...
frame..setMaximum(true); // Maximize this window to fill up the whole desktop area
Setting the method setMaximum(boolean b) of JInternalFrame to "true" , will maximize it.
eg:
JInternalFrame.setMaximum(true)
already suggested above: JInternalFrame#setMaximum(boolean)
Another option: DesktopManager#maximizeFrame(JInternalFrame)
a bit different behavior when JDesktopPane resized.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JInternalFrameMaximumTest {
public JComponent makeUI() {
final JDesktopPane desktop = new JDesktopPane();
Action a1 = new AbstractAction("JInternalFrame#setMaximum") {
#Override public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame("#",true,true,true,true);
desktop.add(f);
f.setVisible(true);
try {
f.setMaximum(true);
} catch(java.beans.PropertyVetoException ex) {
ex.printStackTrace();
}
}
};
Action a2 = new AbstractAction("DesktopManager#maximizeFrame(f)") {
#Override public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame("#",true,true,true,true);
desktop.add(f);
f.setVisible(true);
desktop.getDesktopManager().maximizeFrame(f);
}
};
JToolBar toolbar = new JToolBar("toolbar");
toolbar.add(new JButton(a1));
toolbar.add(new JButton(a2));
JPanel p = new JPanel(new BorderLayout());
p.add(desktop);
p.add(toolbar, BorderLayout.NORTH);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new JInternalFrameMaximumTest().makeUI());
f.setSize(640, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}