I am trying to find a sulotion to translate the void keypressed from c# to java without any succes yet anyone a sulotion?
I want when i press the key 13(enter) that Private void doen() activates once.
import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.*;
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class Paneel extends JPanel {
private static final long serialVersionUID = 1L;
String text;
String AccountName = "default";
String autosavecheck = "";
String iss;
JProgressBar monsterbar, progressbar;
JButton sendknop, clearknop, creditsknop, saveknop, loadknop, restartknop,
disableautosaveknop;
JTextArea commandstextbox, dialoogtextbox;
JTextField naamtextbox, invoertextbox;
JOptionPane resetdialog;
Toolkit toolkit;
Timer timer;
public Paneel() {
setLayout(null);
// --------------------------------
dialoogtextbox = new JTextArea();
dialoogtextbox.setFont(new Font("sansserif", Font.BOLD, 12));
dialoogtextbox.setBounds(12, 12, 838, 207);
dialoogtextbox.list();
invoertextbox = new JTextField(12);
invoertextbox.setBounds(12, 330, 982, 20);
invoertextbox.setEnabled(false);
commandstextbox = new JTextArea();
commandstextbox.setBounds(856, 28, 138, 191);
naamtextbox = new JTextField(12);
naamtextbox.setBounds(772, 263, 220, 20);
toolkit = Toolkit.getDefaultToolkit();
timer1 = new Timer();
toolkit = Toolkit.getDefaultToolkit();
autosave = new Timer();
toolkit = Toolkit.getDefaultToolkit();
monstertimer = new Timer();
toolkit = Toolkit.getDefaultToolkit();
autodisabletimer = new Timer();
sendknop = new JButton("Send");
sendknop.setBounds(12, 260, 75, 23);
sendknop.addActionListener(new sendknopHandler());
add(sendknop);
}
private void keypressed() {
if (e.KeyChar == (char) Keys.Return) {
doen();
}
}
private void doen() {
text = invoertextbox.getText();
invoertextbox.setText("");
}
}
Well if you want to call the method once a JButton is pressed you'd have to add an ActionListener to the JButton and call the method from within the actionPerformed(ActionEvent ae) like this:
jBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called");
//call method here
}
});
or if you want to call the method once a key is pressed on the JPanel use KeyBindings instead of a KeyListener like so:
JPanel panel=...;
...
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "send");
panel.getActionMap().put("send", new MyAction());
...
class MyAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called");
//call method here
}
}
As you can, there are a number of approaches you could try. You didn't really specify on which component you were interested in monitoring, so we've thrown a few different suggestions at you...
In the following example of demonstrated key bindings and the default button of the RootPane.
Unfortunately, the JTextArea consumes the enter key before the root pane is notified, meaning that it won't fire. This is a general issue with text fields as they respond to the enter key action.
The other problem you will face is the fact that I've overridden the default behavior of the JtextField's enter key, meaning it will no longer insert new lines.
public class TestPane extends JPanel {
private JTextArea textArea;
private JButton doneButton;
public TestPane() {
textArea = new JTextArea(10, 50);
doneButton = new JButton("Done");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JScrollPane(textArea), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(4, 4, 4, 4);
add(doneButton, gbc);
InputMap inputMap = textArea.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = textArea.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
actionMap.put("enter", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("I'm done here");
}
});
doneButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("All the way out...");
}
});
}
#Override
public void addNotify() {
super.addNotify();
// This is the button that will be activate by "default", depending on
// what that means for the individual platforms...
SwingUtilities.getRootPane(this).setDefaultButton(doneButton);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setVisible(true);
}
});
}
}
First: get your formatting right, see the instructions for inserting code snippets. Helps those of us who read it :)
I am not entirely sure what you are asking here, but I guess you are trying to get your program to respond to a user clicking any of your buttons. This takes place in the various ActionListeners you should have for buttons. For example, in your case, the sendknopHandler should contain the logic to handle what happens when a user presses this specific button. Inside this class, you will have to filter out the source of the action (i.e. the button pressed), what the action is, and how you want to respond.
learn all about listeners and more specific key listeners
Is "key 13" a button or is it when user types "13"?
if it's a button, just use
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
your statements;
}
}
otherwise use the key listener Peter responded.
a) public Paneel() { missing } after code line add(sendknop);, the same issue is with public class Paneel extends JPanel {,
b) from this code and in this form you'll never listening any event because code isn't runnable, your question is about Java Basic, not about Swing GUI, nor about listener
c) for listening of ENTER key you have to add ActionListener to the JButton
d) for Swing GUI have to use Swing Timer instead of util.Timer, otherwise you have an issue with Concurency in Swing
e) for Swing GUI don't to use KeyListener, there is KeyBindings and with output to the Swing Action
f) otherwise Swing JComponents have got Focus in the Window for KeyListener
Add a key listener to your invoertextbox by adding the following lines to the initialization part of your code:
invoertextbox.addKeyListener(this);
Then extend your class implement the KeyListener interface by adding:
import java.awt.event.KeyListener;
public class Paneel extends JPanel implements KeyListener {
And implement the following methods of the interface within your Paneel class:
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
doen();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
private void doen() {
text = invoertextbox.getText();
invoertextbox.setText("");
}
Consider using keyTyped(KeyEvent) instead of keyPressed(KeyEvent).
"Key typed" events are higher-level and generally do not depend on the
platform or keyboard layout. They are generated when a Unicode
character is entered, and are the preferred way to find out about
character input. In the simplest case, a key typed event is produced
by a single key press (e.g., 'a') […] (JavaDoc for KeyEvent)
Related
I am working on a simple counter swing app. I'm trying to make it so when you click the check box, it will stay on the top and display a message dialog being "On Top" or "Not On Top".
However, when I click the checkbox after compiling and running, both of the messages display, and after clicking OK on both messages, the checkbox isn't even enabled. If I were to remove the showMessageDialog, it would still function properly, but I want to learn how to appropriately implement this.
Thank you in advance. Here is all of the code for the program:
public Class Counter {
JFrame frame;
JPanel panel;
JButton button, clear;
JTextField textC;
JLabel label;
JCheckBox cbox;
boolean topC = false;
int icount = 0;
String scount;
String topStatus = "";
public Counter() {
gui();
setActions();
}
public void gui() {
frame = new JFrame("Counter Program");
panel = new JPanel();
label = new JLabel("Counter");
textC = new JTextField();
textC.setPreferredSize(new Dimension(72,28));
textC.setEditable(false);
button = new JButton("Click");
clear = new JButton("Clear");
cbox = new JCheckBox("Top");
frame.setSize(350,80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.add(label);
panel.add(textC);
panel.add(button);
panel.add(clear);
panel.add(cbox);
frame.setVisible(true);
}
public void setActions() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icount++;
scount = Integer.toString(icount);
textC.setText(scount);
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icount = 0;
textC.setText("");
}
});
cbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
topC = !topC;
if (topC) {
topStatus = "Top";
}
else topStatus = "Not Top";
frame.setAlwaysOnTop(topC);
JOptionPane.showMessageDialog(frame, topStatus, "Top Setting", 1);
}
});
}
public static void main(String[]args) {
new Counter();
}
}
An ItemListener generates two events, one for the selection and one for the unselection (and vice versa). Read the section from the Swing tutorial on How to Write an ItemListener for more information and working exmaples if you really want to use an ItemListener.
Otherwise, use an ActionListener instead, it will only generate a single event.
I'm currently following a java tutorial on how to create a guessing game GUI App. At one point in the instructions however, it says to Set the keyboard focus to the field; I don't know what this means or how to do it. Any clarification would be greatly appreciated.
here's the exact instruction: Focus the user's attention on thePlayer field:
Set the keyboard focus to the field.
here's my code so far:
public class GOM extends JFrame implements ActionListener, KeyListener
{
Container content = this.getContentPane();
//top
JTextField theGuess = new JTextField(10);
JLabel bankroll = new JLabel("");
//bottom
JButton newplayer = new JButton("New Player");
JButton newnumber = new JButton("New Number");
JTextField thePlayer = new JTextField(20);
//center
JTextArea theoutput = new JTextArea("");
//invisible
String playerName;
int theNumber;
int numTries;
int numGames;
double amtRemaining;
Random randomizer()
{
Random rnd = new Random();
return rnd;
}
JScrollPane scrollArea = new JScrollPane(theoutput);
public GOM()
{
this.setVisible(true);
this.setSize(500,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Guess O'Matic");
//top panel
JPanel p1 = new JPanel();
p1.add(theGuess);
p1.add(bankroll);
p1.add(new JLabel("Make Your Guess"));
content.add(p1, BorderLayout.NORTH);
//bottom panel
JPanel p2 = new JPanel();
p2.add(newplayer);
p2.add(newnumber);
p2.add(thePlayer);
content.add(p2, BorderLayout.SOUTH);
// finishing touches
content.add(new JLabel(" "), BorderLayout.WEST);
content.add(new JLabel(" "), BorderLayout.EAST);
content.add(scrollArea, BorderLayout.CENTER);
newplayer.addActionListener(this);
newnumber.addActionListener(this);
thePlayer.addKeyListener(this);
theGuess.addKeyListener(this);
newPlayer();
}
public void newPlayer()
{
theoutput.setText(playerName);
theoutput.setEnabled(false);
theGuess.setEnabled(false);
newnumber.setEnabled(false);
newplayer.setEnabled(false);
theGuess.setBackground(Color.WHITE);
thePlayer.setEnabled(true);
thePlayer.setText(playerName);
thePlayer.setBackground(Color.YELLOW);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
#Override
public void keyReleased(KeyEvent e)
{
}
}
If you have a GUI with several JTextFields and possibly other text components, the keyboard focus can only be on one of those fields at a time. In other words, if you type, only one of the fields can display the caret and then will usually display the typed in text. When a Swing GUI is displayed then the GUI must decide which text component should have focus, and it uses its focus traversal policy to decide this. The default policy usually will put the focus into the first text field created. You can change this by calling requestFocusInWindow() on the text component that you want to hold the focus.
I'm trying to make a key make something happen in a JFrame. Right now I'm just trying to disable a button when you press the left key, but nothing is happening. I thought I have everything right, but it does nothing.
EDIT: I noticed that when I don't click start first, it works. But after you press start, it won't respond.
Here's my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener, KeyListener
{
private static final long serialVersionUID = 1L;
private JPanel p1;
private JButton b1, b2;
private JLabel lb1;
private int a;
private Font font = new Font("Arial", Font.BOLD, 20);
public MyFrame()
{
setLayout(new FlowLayout());
setSize(700,600);
setVisible(true);
setResizable(false);
addKeyListener(this);
setFocusable(true);
p1 = new JPanel(); add(p1);
p1.setBackground(Color.BLACK);
p1.setPreferredSize(new Dimension(650,500));
p1.setFocusable(true);
b1 = new JButton("Start"); add(b1);
b1.addActionListener(this);
b2 = new JButton("Test"); add(b2);
b2.setFocusable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
Graphics g = p1.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(30, 210, 10, 70);
g.fillRect(620, 210, 10, 70);
for(int i=0; i<7; i++)
{
g.fillRect(325, a, 10, 70);
a += 90;
}
g.setFont(font);
g.drawString("Player 1: ", 120, 20);
g.drawString("Player 2: ", 450, 20);
}
public void keyPressed(KeyEvent e)
{
int d = e.getKeyCode();
if(d==KeyEvent.VK_LEFT)
{
b2.setEnabled(false);
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
And here's my Main.java file:
public class Main {
public static void main(String[] arg)
{
MyFrame mf = new MyFrame();
}
}
KeyListener has a lot of problems, with regards to focus (among other things). With Swing, it is preferred to use Key Bindings, which gives us more control over the focus options. There are different InputMaps for WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_IN_FOCUSED_WINDOW. Their names are almost self documenting. So if we were to do
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
then we are getting the InputMap for when the frame is focused. We would then bind a KeyStroke with an Action to that InputMap and the component's ActionMap. For example
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
imap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
ActionMap amap = panel.getActionMap();
Action leftAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
doSomethingWhenLeftIsPressed();
}
};
amap.put("leftAction", leftAction);
Resources
How to use Actions
How to Use Key Bindings
You forgot to tell the JFrame that it should be listening for keys with this line of code:addKeyListener(this);
I'm working in with a JTabbedPane, I need to add a close button in the tabs to close the current one.
I have been searching and as I understand I must extend from JPanel and add the close button as they say here
But, is there a way to add the close buttons extending JTabbedPane or is there a easier way to do it?
Thanks in advance, I really appreciate your time and your help.
Essentially, you're going to need to supply a "renderer" for the tab. Take a look at JTabbedPane.setTabComponentAt(...) for more information.
The basic idea is to supply a component that will be laid out on the tab.
I typically create a JPanel, onto which I add a JLabel (for the title) and, depending on what I want to display, some kind of control that acts as the close action.
tabPane.addTab(title, tabBody);
int index = tabPane.indexOfTab(title);
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
JLabel lblTitle = new JLabel(title);
JButton btnClose = new JButton("x");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
pnlTab.add(lblTitle, gbc);
gbc.gridx++;
gbc.weightx = 0;
pnlTab.add(btnClose, gbc);
tabPane.setTabComponentAt(index, pnlTab);
btnClose.addActionListener(myCloseActionHandler);
Now somewhere else, I establish the action handler...
public class MyCloseActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Component selected = tabPane.getSelectedComponent();
if (selected != null) {
tabPane.remove(selected);
// It would probably be worthwhile getting the source
// casting it back to a JButton and removing
// the action handler reference ;)
}
}
}
Now, you just as easily use any component you like and attach a mouse listener to it and monitor the mouse clicks...
Updated
The above example will only remove the currently active tab, there are a couple of ways to fix this.
The best is to probably provide some means for the action to find the tab it's associated with...
public class MyCloseActionHandler implements ActionListener {
private String tabName;
public MyCloseActionHandler(String tabName) {
this.tabName = tabName;
}
public String getTabName() {
return tabName;
}
public void actionPerformed(ActionEvent evt) {
int index = tabPane.indexOfTab(getTabName());
if (index >= 0) {
tabPane.removeTabAt(index);
// It would probably be worthwhile getting the source
// casting it back to a JButton and removing
// the action handler reference ;)
}
}
}
This uses the name of tab (as used with JTabbedPane#addTab) to find and then remove the tab and its associated component...
I found a tab example (from the java site) that appears to do that, at least in theirs. (Though I thought, when I tried it in the past, that it also closed the currently selected tab, though it works properly when you run their example, though I think when I updated it to work on a tabbed java notepad, it was closing the currently selected tab, though maybe I did it wrong.
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
Yes, my thing is working now! This WILL work for the actual tab, rather than the currently selected tab!
Hopefully you have got the answer to your question. I want to give a link that was very useful for me.
JTabbedPane with a close button
Here is some code as well.
public static void createAndShowGUI()
{
JFrame frame = new JFrame("Tabs");
frame.setMinimumSize(new Dimension(500, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel();
panel.setOpaque(false);
tabbedPane.add(panel);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel), getTitlePanel(tabbedPane, panel, "Tab1"));
JPanel panel1 = new JPanel();
panel1.setOpaque(false);
tabbedPane.add(panel1);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel1), getTitlePanel(tabbedPane, panel1, "Tab2"));
JPanel panel2 = new JPanel();
panel2.setOpaque(false);
tabbedPane.add(panel2);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel2), getTitlePanel(tabbedPane, panel2, "Tab3"));
JPanel panel3 = new JPanel();
panel3.setOpaque(false);
tabbedPane.add(panel3);
tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel3), getTitlePanel(tabbedPane, panel3, "Tab4"));
frame.add(tabbedPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
I made some changes in the code of oracle.
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
Giving the possibility to add an icon to the tab , plus the close tab button. Hope that helps.
public static void addTag(JTabbedPane tab, String title, Icon icon, int index){
MouseListener close = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//your code to remove component
//I use this way , because I use other methods of control than normal: tab.remove(int index);
}
};
final ButtonClose buttonClose = new ButtonClose (title, icon, close );
tab.setTabComponentAt(index, buttonClose);
tab.validate();
tab.setSelectedIndex(index);
}
public class ButtonClose extends JPanel {
public ButtonClose(final String title, Icon icon, MouseListener e) {
JLabel ic = new JLabel(icon);
ic.setSize(icone.getIconWidth(), icone.getIconHeight());
JLabel text= new JLabel(title);
text.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
ButtonTab button = new ButtonTab();
button.addMouseListener(e);
button.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
JPanel p = new JPanel();
p.setSize(getWidth() - icone.getIconWidth(), 15);
p.add(text);
p.add(button);
add(ic);
add(p);
}
private class ButtonTab extends JButton {
public ButtonTab() {
int size = 13;
setPreferredSize(new Dimension(size, size));
setToolTipText("Close");
setUI(new BasicButtonUI());
setFocusable(false);
setBorderPainted(false);
addMouseListener(listener);
setRolloverEnabled(true);
}
#Override
public void updateUI() {
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
if (getModel().isPressed()) {
g2.translate(1, 1);
}
g2.setStroke(new BasicStroke(2));
g2.setColor(new Color(126, 118, 91));
if (getModel().isRollover()) {
g2.setColor(Color.WHITE);
}
int delta = 3;
g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
g2.dispose();
}
}
private final MouseListener listener = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setContentAreaFilled(true);
button.setBackground(new Color(215, 65, 35));
}
}
#Override
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setContentAreaFilled(false); //transparent
}
}
};
}
Check out Peter-Swing here. It has a JClosableTabbedPane class in it, as well as many others.
When you download the jar file you can run it and have examples of all the classes.
You can have a JLabel named "x" and use the mouseListener
private final JLabel l = new JLabel(); // this is the label for tabbedPane
private final JLabel b = new JLabel("x");//Close Button
if (closeable)
{
b.setToolTipText("Click to close");
b.setOpaque(false);
b.setBackground(Color.gray);
b.addMouseListener(new MouseAdapter()
{
#Override
public void mouseExited(MouseEvent e)
{
b.setBorder(bordere);
b.setOpaque(false);
}
#Override
public void mouseEntered(MouseEvent e)
{
b.setBorder(borderl);
}
#Override
public void mouseReleased(MouseEvent e)
{
b.setOpaque(false);
b.repaint();
if (b.contains(e.getPoint()))
{
b.setBorder(borderl);
if (confirmTabClosing())
{
tab.remove(tabIndex());
if(tab.getTabCount() == 0)
spacialTabComponent.maximizeOrRestore.doClick();
}
}
else
b.setBorder(bordere);
}
#Override
public void mousePressed(MouseEvent e)
{
b.setOpaque(true);
b.repaint();
}
});
b.setBorder(bordere);
add(b, getLeftAlignedBothFilledGBC(1, 0, new Insets(0, 0, 0, 0), 0, 0));
}
}
jbCloseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int index = jtbMainTabbedPane.indexOfTabComponent(jbCloseButton);
jtbMainTabbedPane.remove(index);
}
});
I have a JFrame with three JButtons on it. I have set txtSearch (a JTextField component) to have the focus when JFrame loads. One of the buttons is set as the default button. This is my code:
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
// btnRefresh.setMnemonic(KeyEvent.VK_R); // Even if this line
// is not commented, but
// still the event wouldn't fire.
this.getRootPane().setDefaultButton(btnRefresh);
}
When it loads, the button is just selected, but it did nothing when the Enter key was being pressed. How do I correctly implement it?
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(this, "Pressed!");
// Other codes here (Replace by JOptionPane)
}
What component has focus when the JFrame comes up? I ask because some components "eat" the Enter key event. For example, a JEditorPane will do that.
Also, when you assign an ActionListener to JTextField, the ActionListener will be called instead of the DefaultButton for the root pane. You must choose either to have an ActionListener or a DefaultButton, but you can't have both fire for the same JTextField. I'm sure this applies to other components as well.
I don't see what you are doing incorrectly from what is posted. Here is a short example that works. Perhaps it will reveal something useful to you.
import java.awt.BorderLayout;
public class ExampleFrame extends JFrame
{
private JPanel m_contentPane;
private JTextField m_textField;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
ExampleFrame frame = new ExampleFrame();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleFrame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
m_contentPane = new JPanel();
m_contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
m_contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(m_contentPane);
m_textField = new JTextField();
m_contentPane.add(m_textField, BorderLayout.NORTH);
m_textField.setColumns(10);
JButton btnNewButton = new JButton("Default");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(ExampleFrame.this, "Default.");
}
});
m_contentPane.add(btnNewButton, BorderLayout.CENTER);
JButton btnNewButton_1 = new JButton("Not default");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(ExampleFrame.this, "Not default.");
}
});
m_contentPane.add(btnNewButton_1, BorderLayout.WEST);
m_textField.requestFocus();
getRootPane().setDefaultButton(btnNewButton);
}
}