Hi I am trying to make java desk top application where I am using 3 JButtons. I want that when I click any JButton it should change the color of that button and if I click on any other JButton then previous clicked button should be like before and recently clicked button change its color until another JButton is clicked
How can I achieve this
here is my button code
b1 = new JButton("Ok");
b1.setBounds(800, 725, 100, 40);
b1.setForeground(Color.BLACK);
c.add(b1);
b2 = new JButton("Print");
b2.setBounds(925, 725, 100, 40);
b2.setForeground(Color.BLACK);
c.add(b2);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
b1.setBackground(Color.BLUE);
JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
b2.setBackground(Color.BLUE);
JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
}
});
This is actually more tricky then it sounds. Some look and feels don't use the background color property when rendering the buttons (for example Windows)
A possible solution might be to use a ButtonGroup and JToggleButton, which will ensure that only one button is selected at a time and allow you to monitor the selected states of the buttons, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ToggleButton {
public static void main(String[] args) {
new ToggleButton();
}
public ToggleButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JToggleButton b1 = new JToggleButton("Ok");
b1.setContentAreaFilled(false);
b1.setOpaque(true);
b1.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (b1.isSelected()) {
b1.setBackground(Color.BLACK);
} else {
b1.setBackground(null);
}
}
});
final JToggleButton b2 = new JToggleButton("Print");
b2.setContentAreaFilled(false);
b2.setOpaque(true);
b2.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (b2.isSelected()) {
b2.setBackground(Color.BLUE);
} else {
b2.setBackground(null);
}
}
});
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(b1);
frame.add(b2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Another solution might be to use JRadioButton instead, which is generally used to indicate a single selection from a group of options.
See How to Use Buttons, Check Boxes, and Radio Buttons
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
b1.setBackground(Color.BLUE);
b2.setBackground(Color.BLACK);
JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
b2.setBackground(Color.BLUE);
b1.setBackground(Color.BLACK);
JOptionPane.showMessageDialog(frame,"Welcome to allhabad High Court");
}
});
Related
I am trying to get the buttons to at least execute something when they are pressed and BlueJ doesn't show any errors, but when I execute the Program and I try to press the buttons, nothing happens. I am really unsure why that is the case. I would appreciate any help!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class MainMenu
{
JFrame frame= new JFrame();
JButton button = new JButton("Singleplayer");
JButton button2 = new JButton("Multiplayer");
MainMenu(){
prepareGUI();
}
public void prepareGUI(){
frame.setTitle("Game");
frame.getContentPane().setLayout(null);
frame.add(button);
frame.add(button2);
button.setBounds(100,200,100,40);
button2.setBounds(200,200,100,40);
frame.setVisible(true);
frame.setBounds(200,200,400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setUpButtonListeners(){
ActionListener buttonlistener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.getContentPane().setBackground(Color.green);
System.out.println("Singleplayer Selected");
}
};
ActionListener buttonlistener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
frame.getContentPane().setBackground(Color.red);
System.out.println("Multiplayer Selected");
}
};
button.addActionListener(buttonlistener);
button2.addActionListener(buttonlistener2);
}
public class MainClass {
public void main(String args[] )
{
new MainMenu();
}
}
}
setUpButtonListeners() are not executed in the program. So action listeners are not available. you can include setUpButtonListeners() in prepareGUI method.
I was designing a program which has multiple layers(panels), and I want these panels to be keyboard sensitive so that I can press ESC to exit to the main menu (First panel) at any time.
Here is the switch panel code that I've written:
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
}
I know that in order for the panel to be keyboard sensitive, it needs to be focusable.
Here's the code I have written for the initialisation of one of the panels:
panel2 = new JPanel();
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if(e.getKeyCode()==KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
I have deleted most of the unrelated functions and codes.
What I wish to accomplish is that when the switch page button is clicked, the switchPane method is executed, and the new panel automatically gets the focus with the requestFocusInWindow(); command, so that user can type ESC to return to the main menu.
When I tried to run the program, it turns out that for the first time I entered a sub-panel, it can not get the focus and does not respond to the keyboard. However, if I return to the main panel using the return button and re-enter the same sub-panel, this time it automatically gets the focus and is responding to the keyboard.
I have no idea why the program shows such behaviour. The following is the full program. Please notice that in the full program I also added a click to get focus function which works. However, I wish the newly opened panel can automatically get the focus and responding to the keys without the user actually clicking the panel.
import java.awt.*;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class mainFrame {
private JFrame frmDavidsAppstore;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmDavidsAppstore.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmDavidsAppstore = new JFrame();
frmDavidsAppstore.setResizable(false);
frmDavidsAppstore.setTitle("David's appstore");
frmDavidsAppstore.setBounds(100, 100, 800, 600);
frmDavidsAppstore.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmDavidsAppstore.getContentPane().setLayout(new CardLayout(0, 0));
panel1 = new JPanel();
panel1.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel1, "name_83127645466169");
panel1.setLayout(null);
panel1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel1: " + KeyEvent.getKeyText(e.getKeyCode()));
}
});
JButton button2 = new JButton("Open page 2");
button2.setFont(new Font("Tahoma", Font.PLAIN, 18));
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel2);
}
});
button2.setBounds(279, 344, 236, 50);
panel1.add(button2);
JButton button3 = new JButton("Open page 3");
button3.setFont(new Font("Tahoma", Font.PLAIN, 18));
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel3);
}
});
button3.setBounds(279, 432, 236, 50);
panel1.add(button3);
JLabel background = new JLabel("");
background.setIcon(new ImageIcon(mainFrame.class.getResource("/images/background_main.jpg")));
background.setBounds(0, 0, 794, 565);
panel1.add(background);
panel2 = new JPanel();
panel2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel2.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(130, 104, 533, 270);
panel2.add(scrollPane_1);
JTextArea txtrIAmPage = new JTextArea();
txtrIAmPage.setEditable(false);
scrollPane_1.setViewportView(txtrIAmPage);
txtrIAmPage.setText("I am page2");
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
panel3 = new JPanel();
panel3.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel3.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel3.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel3, "name_83334788966651");
panel3.setLayout(null);
panel3.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel3: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(130, 104, 533, 270);
panel3.add(scrollPane);
JTextArea txtrIAmPage_1 = new JTextArea();
scrollPane.setViewportView(txtrIAmPage_1);
txtrIAmPage_1.setText("I am page3");
JButton button = new JButton("Return to main page");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
button.setBounds(279, 431, 236, 50);
panel3.add(button);
}
}
I have been working on it for a day now and couldn't figure out why. Thank you guys so much for any help or advices.
Apreciated!
Problem solved!!! You need to add .setVisible(true); before .requestFocusInWindow(); in order for it to work!
I am trying to get a JTextField to show over a JButton when I click the button. I have that working, but when I click out of the button it still stays visible. I'm using a MouseListener event so once I exit the button I want JTextField to become transparent again, but it stays visible.
My code:
import java.awt.EventQueue;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseEvent;
public class magicalJtextField extends JFrame implements MouseListener{
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
magicalJtextField frame = new magicalJtextField();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public magicalJtextField() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(78, 78, 89, 30);
contentPane.add(textField);
textField.setColumns(10);
JButton button = new JButton("");
//button transparent
// button.setOpaque(false);
// button.setContentAreaFilled(false);
// button.setBorderPainted(false);
button.setBounds(78, 78, 89, 23);
button.addMouseListener(this);
contentPane.add(button);
textField.setVisible(false);
}
public void mouseEntered(MouseEvent e)
{
//button.setText("Mouse Entered");
//button.setBackground(Color.CYAN);
// textField.setVisible(true);
}
public void mouseExited(MouseEvent e)
{
textField.setVisible(false);
}
public void mouseClicked(MouseEvent e)
{
textField.setVisible(true);
}
public void mousePressed(MouseEvent e)
{
textField.setVisible(true);
}
public void mouseReleased(MouseEvent e)
{
textField.setVisible(true);
}
}
I suggest a CardLayout for the Jbutton-JTextField magic trick (edit: I actually saw the recommendations in the comments only after I posted because it was so obvious and on an answer). Pressing the button will switch the card and then exiting the text field area with the mouse will switch it again.
public class Example extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.add(new Example());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
});
}
public Example() {
CardLayout cards = new CardLayout(5, 5);
JPanel panel = new JPanel(cards);
JButton button = new JButton("");
JTextField textField = new JTextField(10);
button.addActionListener(e -> {
cards.next(panel);
textField.requestFocusInWindow();
});
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
cards.next(panel);
}
});
panel.add(button);
panel.add(textField);
add(panel);
}
}
As you were told by Andrew Thompson, don't use null layouts and don't specify bounds. Use a proper layout manager to do this for you.
Use an ActionListener to react on the button click: If you receive a click, make the button invisible and the textField visible.
Then attach the MouseListener to the textField and not the button and only implement mouseExited (all others empty). When you receive this event make the textField invisible and the button visible again.
To abstract this problem, I put 2 buttons. One is called "Add & toTop", another is called "toTop"
And there is no text in the textArea at the very beginning.
And I add the actionListener for "Add & toTop" button like this:
btn1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textArea1.setText("jhggjhg\nhugffsrdtfg\ngfdrtdf\nhgftrsdf\nytfresrdcfvg\nuytyrdtesrdfgg\ntdrfygvhct\njh"
+ "gfda\njftyuyiugcf\nhfuygihvftyughbuy\nhgyuftydfhgfyc\ndstryrfdts");
//A long enough String
JScrollBar jb = scrollPane1.getVerticalScrollBar();
jb.setValue(jb.getMinimum());
scrollPane1.repaint();
}
});
So the function of the first button is :"Add some text and Scroll to Top"
But it will only add text but will not scroll to top
However for the second button, I add a actionListener like this:
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JScrollBar VerticalScrollBar = scrollPane1.getVerticalScrollBar();
VerticalScrollBar.setValue(VerticalScrollBar.getMinimum());
scrollPane1.repaint();
}
});
So, I press the second button after pressing the first button, the second button will perform well.
And I really feel confused that why the first button will not scroll to top :<
A simple solution might be to use JTextArea#setCaretPosition, for example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea ta;
public TestPane() {
setLayout(new BorderLayout());
ta = new JTextArea(5, 20);
add(new JScrollPane(ta));
JButton btn = new JButton("Add and to top");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ta.setText("jhggjhg\nhugffsrdtfg\ngfdrtdf\nhgftrsdf\nytfresrdcfvg\nuytyrdtesrdfgg\ntdrfygvhct\njh"
+ "gfda\njftyuyiugcf\nhfuygihvftyughbuy\nhgyuftydfhgfyc\ndstryrfdts");
ta.setCaretPosition(0);
}
});
add(btn, BorderLayout.SOUTH);
}
}
}
I had a play around with scrollRectToVisible, but ended up having to use SwingUtilites.invokeLater to make it work, for example...
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ta.scrollRectToVisible(new Rectangle(0, 0, 10, 10));
}
});
so I'd say setCaretPosition in this case is the simpler solution
I'm learning Swing class now and everything about it. I've got this toy program I've been putting together that prompts for a name and then presents a JOptionPane with the message "You've entered (Your Name)".
The submit button I use can only be clicked on, but I'd like to get it to work with the Enter button too. I've tried adding a KeyListener, as is recommended in the Java book I'm using (Eventful Java, Bruce Danyluk and Murtagh).
This is my code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName));
submit.addKeyListener(new SubmitButton(textBoxToEnterName));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
And this is the actionListener, keyListener class:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SubmitButton implements ActionListener, KeyListener {
JTextField nameInput;
public SubmitButton(JTextField textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
}
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
There is a simple trick for this. After you constructed the frame with all it buttons do this:
frame.getRootPane().setDefaultButton(submitButton);
For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.
And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
}
}
UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:
SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);
You can use the top level containers root pane to set a default button, which will allow it to respond to the enter.
SwingUtilities.getRootPane(submitButton).setDefaultButton(submitButton);
This, of course, assumes you've added the button to a valid container ;)
UPDATED
This is a basic example using the JRootPane#setDefaultButton and key bindings API
public class DefaultButton {
public static void main(String[] args) {
new DefaultButton();
}
public DefaultButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton button;
private JLabel label;
private int count;
public TestPane() {
label = new JLabel("Press the button");
button = new JButton("Press me");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
gbc.gridy++;
add(new JButton("No Action Here"), gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
InputMap im = button.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = button.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "spaced");
am.put("spaced", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
}
#Override
public void addNotify() {
super.addNotify();
SwingUtilities.getRootPane(button).setDefaultButton(button);
}
protected void doButtonPressed(ActionEvent evt) {
count++;
label.setText("Pressed " + count + " times");
}
}
}
This of course, assumes that the component with focus does not consume the key event in question (like the second button consuming the space or enter keys
In the ActionListener Class you can simply add
public void actionPerformed(ActionEvent event) {
if (event.getSource()==textField){
textButton.doClick();
}
else if (event.getSource()==textButton) {
//do something
}
}
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
Without a frame this works for me:
JTextField tf = new JTextField(20);
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
String[] options = {"Ok", "Cancel"};
int result = JOptionPane.showOptionDialog(
null, tf, "Enter your message",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,0);
message = tf.getText();
I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key
textField_in = new JTextField();
textField_in.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getExtendedKeyCode());
if (arg0.getKeyCode()==10) {
String name = textField_in.getText();
textField_out.setText(name);
}
}
});
textField_in.setBounds(173, 40, 86, 20);
frame.getContentPane().add(textField_in);
textField_in.setColumns(10);