How to link a hotkey to a button in java? - java

I have four radio buttons and they're all part of a radioGroup. How can I link hotkeys to each of the buttons? What I want to do is link the keys '1', '2', '3' and '4' to each corresponding radiobutton.
buttonGroup1 = new javax.swing.ButtonGroup();
quizBut1 = new javax.swing.JRadioButton();
quizBut2 = new javax.swing.JRadioButton();
quizBut4 = new javax.swing.JRadioButton();
quizBut3 = new javax.swing.JRadioButton();

Use a KeyListener - you can attach them to just about any component in Swing.
What you'll probably do is attach a KeyListener to the primary JFrame in your application to capture all keypresses, and depending on which key was pressed, you will then trigger changes in the UI accordingly (e.g the selecting of a given radio button).
It's important that you attach the KeyListener to a container that will have keybaord focus pretty much all the time. You cannot, in this case, attach the KeyListener to the radio buttons themselves because the KeyListeners only see events for which they have focus. When a KeyEvent isn't absorbed by a given object, the KeyEvent is then passed on to its parent component to see if it wants to do anything with the event, and on and on all the way up to the application's window. If no KeyListener does anything with the event and you've gone all the way to the root of the component hierarchy, then nothing happens in response to the keypress and the event is essentially discarded.

as well, you could use ActionMap and KeyStroke. Some rough snippet, modify it:
class KeyAction extends AbstractAction {
JRadioButton b;
KeyAction(JRadioButton b) {
super();
this.b = b;
}
#Override
public void actionPerformed(ActionEvent e) {
b.setSelected(true);
}
}
b1.setAction(new KeyAction(b1));
b2.setAction(new KeyAction(b2));
b3.setAction(new KeyAction(b3));
bindHotkey('1', "1", b1.getAction());
bindHotkey('2', "2", b2.getAction());
bindHotkey('3', "3", b3.getAction());
..............
void bindHotkey(char keyChar, String name, Action action) {
KeyStroke ks = KeyStroke.getKeyStroke(keyChar);
container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, name);
container.getActionMap().put(name, action);
}

You can use this also http://pastebin.com/UvkjD0g5

Related

Why are the keybindings not working with CardLayout?

In my question How do I draw on a JPanel from multiple outside classes? Frakcool gave me the advice to use key bindings, and one thing didn't work: When the JButton put another JPanel infront of the frame, the Keybinding didn't respond. This is the code:
private JFrame frame;
private JPanel[] statePanels;
private CardLayout layout;
private JPanel mainPanel;
private JButton button;
private String status;
void initAndShow()
{
//Init stuff
mainPanel = new JPanel(layout);
statePanels = new JPanel[2];
button = new JButton("Exit");
status = "Menu";
button.addActionListener(e -> {
status = status.equals("Menu") ? "World" : "Menu";
layout.show(mainPanel, status);
});
statePanels[0] = new OutWorldHandler();
statePanels[1] = new InWorldHandler();
mainPanel.add(statePanels[0], "Menu");
mainPanel.add(statePanels[1], "World");
mainPanel.getInputMap().put(KeyStroke.getKeyStroke('f'), "close");
mainPanel.getActionMap().put("close", this);
frame.add(mainPanel);
frame.add(button, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("hi");
}
The expected output was that when I allways pressed f the console would print out "hi", but it only did as long as I didn't press the button
Key bindings aren't particularly complex, but they can take a little bit of getting use to. To this end, it's useful to have How to Use Key Bindings and the JavaDocs for JComponent on hand, for reference.
One of the goals of the key bindings API is configurability, allowing us more control over determining when a key stroke should trigger an event.
The JComponent#getInputMap method returns a mapping which is bound to the "when has focused" context. This means that the component will need to have focus (and be focusable obviously) before a binding will be triggered.
If you want the binding to be triggered at a different level, then you need to use JComponent#getInputMap(int) and pass it one of the three available contexts:
JComponent.WHEN_IN_FOCUSED_WINDOW
JComponent.WHEN_FOCUSED
JComponent. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
Which you use will depend on your needs, but I'm generally lazy and go for JComponent.WHEN_IN_FOCUSED_WINDOW when I want a "global" state
The solution that worked for me: I simply added a statement to the button.addActionListener lambda that put the focus on mainPanel: mainPanel.grabFocus();.
The full code then looked something like this:
button.addActionListener(e -> {
status = status.equals("Menu") ? "World" : "Menu";
layout.show(mainPanel, status);
button.setText("Exit " + status);
mainPanel.grabFocus();
});

Handle RadioButton events after button clicked

help,
my questions are:
why isn't itemStateChanges triggered, I tried to put it in the inner class ButtonHandler and also in RadioButtonHandler Im having trouble with it, what is the right way to do it?
I want to trigger and check the marked JRadioButtons after the user click the "check" button.
What is the right way to check which button was clicked, I feel like comparing the strings is bad programming practise. Maybe using an ID ?
How should I make a "reset" button(start over), I want to uncheck all radio buttons and run the constructor once again.
Thank you for your help !
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ExamFrame extends JFrame {
static ArrayList<Question> qArrList;
JRadioButton a1,a2,a3,a4;
public ExamFrame() {
super("Quiz");
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
Exam exam = new Exam();
qArrList = exam.getExam();
int count=0;
for(Question q : qArrList){
count++;
JLabel questionLabel = new JLabel(count+". "+q.getQustion()); //swing constant ?
ArrayList<String> ansRand = q.getAllRandomAns();
a1 = new JRadioButton(ansRand.get(0));
a2 = new JRadioButton(ansRand.get(1));
a3 = new JRadioButton(ansRand.get(2));
a4 = new JRadioButton(ansRand.get(3));
add(questionLabel);
add(a1);add(a2,gbc);add(a3);add(a4);
ButtonGroup radioGroup = new ButtonGroup(); //logical relationship
radioGroup.add(a1);radioGroup.add(a2);radioGroup.add(a3);radioGroup.add(a4);
}
//buttons:
JButton checkMe = new JButton("Check Exam");
JButton refresh = new JButton("Start Over");
ButtonHandler handler = new ButtonHandler();
checkMe.addActionListener(handler);
refresh.addActionListener(handler);
add(checkMe);
add(refresh);
}
/** Listens to the radio buttons. */
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Start Over")){ //id?
//how to do this?
}
else{
RadioButtonHandler handler = new RadioButtonHandler();
a1.addItemListener(handler);
System.out.println("success?");
}
JOptionPane.showMessageDialog(ExamFrame.this, String.format("You pressed: %s", e.getActionCommand()));
}
public void itemStateChanged(ItemEvent e) //can i add it here?
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("yes?"));
System.out.println("success!");
}
}
public class RadioButtonHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("radio state changed"));
}
}
}
why "itemStateChanges" isn't triggered, i tried to put it in the inner
class "ButtonHandler" and also in "RadioButtonHandler" Im having
troubles with it, what is the right way to do it? I want to trigger
and check the marked JRadioButtons after the user click the "check"
button.
ButtonHandler is implemented with ActionListener only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent) function belongs to ItemListener. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener. However, one more thing to note, that JButton doesn't respond to ItemListener but JRadioButton will. Because this Item events are fired by components that implement the ItemSelectable interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like
comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource(), check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String) function and check the name you were expecting. Of-course you should assign the name using setName(String) after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all
radio buttons and run the constructor once again.
Well you are working with ButtonGroup. And ButtonGroup has a nice function: clearSelection() to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener implemented class, Yes i can see that But:
i can not see that you have actually registered an instance of that class(a1.addItemListener(handler);) to any component before performing any action on the component to which ButtonHandler is registered to: checkMe, refresh
In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with JButton.setActionCommand(String) function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial:
How to Write an ItemListener
How to Write an ActionListener
How to Use the ButtonGroup Component

How i handle keypress event for Jcombobox in java

I want to add item to JCombobox , that item is what I typed in JCombobox which is item to be add. this jCombox box is editable.
How can i do this.
Ok i tryied add KeyPress event for this JCombo box but it doesn't respose
private void jbcBOXKeyTyped(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == 13) {
System.out.println("Keypress");
jbcBOX.addItem(jbcBOX.getSelectedItem().toString());
}
}
Made a short example hope it helps.
Basically just adds ActionListener to JComboBox the ActionListener is called whenever an item is selected or added. In the ActionListener we simply check if there is an item that matches the currently selected item, if not then add the item to JComboBox if a match is found then do nothing:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class EditableJComboBox {
public EditableJComboBox() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Editable JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String labels[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
final JComboBox comboBox = new JComboBox(labels);
comboBox.setEditable(true);
comboBox.addActionListener(new ActionListener() {
private boolean found = false;
#Override
public void actionPerformed(ActionEvent actionEvent) {
String s = (String) comboBox.getSelectedItem();
for (int i = 0; i < comboBox.getItemCount(); i++) {
if (comboBox.getItemAt(i).toString().equals(s)) {
found = true;
break;
}
}
if (!found) {
System.out.println("Added: " + s);
comboBox.addItem(s);
}
found = false;
}
});
frame.add(comboBox);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new EditableJComboBox();
}
});
}
}
This is explained in the Combobox tutorial. No need for dirty KeyListeners and checks for the enter key.
You make the combobox editable
You add an ActionListener which will be triggered when the enter key is hit
In your ActionListener you can update the model
Or to quote that tutorial more literally
JComboBox patternList = new JComboBox(patternExamples);
patternList.setEditable(true);
patternList.addActionListener(this);
An editable combo box fires an action event when the user chooses an item from the menu and when the user types Enter. Note that the menu remains unchanged when the user enters a value into the combo box. If you want, you can easily write an action listener that adds a new item to the combo box's menu each time the user types in a unique value.
It's worse than even this says - it seems (from using Netbeans) keyTyped etc events simply don't fire. I imagine a great number of people are here wondering why they can catch java.awt.event.KeyEvent.getKeyChar() on a JTextField but using exactly the coresponding part of the GUI Builder (in Netbeans) for a JComboBox gets them absolutely nothing!
Handling Events on a Combo Box
...
Although JComboBox inherits methods to register listeners for
low-level events — focus, key, and mouse events, for example — we
recommend that you don't listen for low-level events on a combo box.
Here's why: A combo box is a compound component — it is comprised of
two or more other components. The combo box itself fires high-level
events such as action events. Its subcomponents fire low-level events
such as mouse, key, and focus events. The low-level events and the
subcomponent that fires them are look-and-feel-dependent. To avoid
writing look-and-feel-dependent code, you should listen only for
high-level events on a compound component such as a combo box. For
information about events, including a discussion about high- and
low-level events, refer to Writing Event Listeners.

Adding Keyboard support to Java Swing application regardless of Focus

I have a JFrame with multiple panels that accumulates in a fairly complex Swing UI. I want to add Keyboard support so that regardless of component focus a certain Key press, for example the [ENTER] key, causes a listener to react.
I tried adding a KeyListener to the JFrame but that doesn't work if another JComponent is selected which changes focus.
Is there a proper way to do this?
Registering a KeyEventDispatcher with the KeyboardFocusManager allows you to see all key events before they are sent to the focused component. You can even modify the event or prevent it from beeing delivered to the focused component:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
//Get the char which was pressed from the KeyEvent:
e.getKeyChar();
//Return 'true' if you want to discard the event.
return false;
}
});
If you just want to get the key inputs for one window / component or just for specific keys, you can use KeyBindings as kleopatra suggested. As an example on how to register to the keyboard event on Enter pressed (You may use any VK_ provided by KeyEvent, for modifiers [alt, ctrl, etc.] see InputEvent) see:
JFrame frame = new JFrame(); //e.g.
JPanel content = (JPanel)frame.getContentPane();
content.getInputMap().put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,0),"enterDown");
content.getActionMap().put("enterDown",new AbstractAction() {
private static final long serialVersionUID = 1l;
#Override public void actionPerformed(ActionEvent e) {
//This action is called, as the Enter-key was pressed.
}
});
The way I do it is to make the JFrame focusable and append the listener to it. Then, iterate through all the JFrame children and make everything else not focusable.
Of course this only works if you don't have text boxes or similar as they will become non editable.

using java swing

I need to put a value in to my class from UI (Swing) and then start my method by clicking a button. What should I do?
Getting started with swing
Here's a super simple example of a text field and a button that, when clicked, will get the text value then you can all the method you'd like to pass that value to.
public class ButtonExample extends JPanel
{
private JTextField _text;
public ButtonExample()
{
_text = new JTextField();
setLayout( new BorderLayout() );
add( _text, BorderLayout.NORTH );
add( new JButton( new CaptureTextAction() ), BorderLayout.SOUTH );
}
private class CaptureTextAction extends AbstractAction
{
private CaptureTextAction()
{
super( "Click Me" );
}
#Override
public void actionPerformed( ActionEvent ae )
{
String textToCapture = _text.getText();
// do something interesting with the text
}
}
}
Swing is just the user interface you provide to to your app.
it works like this....
you have buttons, panels and all the stuff you need for providing a proper interface, which means if you need to take text input you'll put textfield or textArea in your UI
swing applications are based on events, thats the basic difference between console based and window based applications, a console based application is sequential it compiles and then executes code sequentially it has no regard of how you interact with it.
a swing application on the other hand is event based, until any event is fired and caught it won't do anything, in java you just handle the event, which means what happens after an event occurs is decided by the programmer.
suppose there is a button click event fires and there is a listener attached to the element then the actionPerformed function gets called and it is executed
suppose you want to get the user name from the app
JButton btnSubmit = new JButton("Submit");
JTextField txtName = new JTextField("", 4);
btnSubmit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String name = txtName.getText();//see below for explanation
printInfo();//write the function call statements here if you want them to be executed when button is clicked
}
});
whenever button is clicked or more generally any event occurs on the button then it creates a string object in the string pool and assigns to it the value of the text field at the time when the button was clicked

Categories

Resources