JButton's ActionListener - java

In the code below, when both _uiChkTestAction and _uiChkTestItem JCheckBox are unselected, clicking bu1 button make them both selected, but clicking bu2 button does not change _uiChkTestItem JCheckBox from being unselected to selected.
So, is there something wrong with my code ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class TestActionItemListener
{
public static void main(String[] _args)
{
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame _fra = new JFrame("Testing");
_fra.setSize(500, 500);
_fra.setLayout(new FlowLayout());
final JCheckBox _uiChkTestAction = new JCheckBox("ActionListener");
_uiChkTestAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _ev)
{
System.out.println("State by ActionListener: " + _uiChkTestAction.isSelected());
}
});
final JCheckBox _uiChkTestItem = new JCheckBox("ItemListener");
_uiChkTestItem.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
System.out.println("State by ItemListener: " + _uiChkTestAction.isSelected());
}
});
JButton bu1 = new JButton("actionlistener bu");
bu1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
_uiChkTestAction.setSelected(true);
}
});
JButton bu2 = new JButton("itemlistener bu");
bu1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
_uiChkTestItem.setSelected(true);
}
});
_fra.add(_uiChkTestAction);
_fra.add(_uiChkTestItem);
_fra.add(bu1);
_fra.add(bu2);
_uiChkTestAction.setSelected(true);
_uiChkTestItem.setSelected(true);
_fra.setVisible(true);
}}
);
}
};

You add both of your listeners to the same button bu1 iso adding one to bu1 and one to bu2

You're adding a listener to bu1 twice. Add the second one to bu2.

Related

Java FocusListener and KeyListener don't work if I add a JButton

I have two classes that implement KeyListener and FocusListener interfaces. Neither works, but if I don't add the JButton by commenting or removing this: add(whiteJButton), then they do work. Could someone explain to me why this happens? Thanks in advance.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JFrames {
public static void main(String[] args) {
JFrame myJFrame = new JFrame("MyJFrame");
myJFrame.setBounds(400, 400, 500, 500);
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyJPanel myJPanel = new MyJPanel();
myJFrame.add(myJPanel);
// Doesn't work
myJFrame.addKeyListener(new MyKeyListener());
// Doesn't work
myJFrame.addFocusListener(new MyFocusListener());
myJFrame.setVisible(true);
}
static class MyJPanel extends JPanel {
public MyJPanel() {
JButton whiteJButton = new JButton("WHITE");
add(whiteJButton);
whiteJButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.WHITE);
}
});
}
}
}
class MyKeyListener implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped: " + e.getKeyChar());
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed: " + e.getKeyChar());
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased: " + e.getKeyChar());
}
}
class MyFocusListener implements FocusListener {
#Override
public void focusGained(FocusEvent e) {
System.out.println("focusGained");
}
#Override
public void focusLost(FocusEvent e) {
System.out.println("focusLost");
}
}
The problem is that the button steals focus from the JFrame, preventing the focus listener from working (focus is already gone). Some solutions if you absolutely need to use a KeyListener are kludges, including making the JButton not focusable: whiteJButton.setFocusable(false);, but if you do this, you need to do this for all components added. And yes you can request focus as the other answer suggests, but it should be requestFocusInWindw(), not requestFocus() (many similar questions explain why this is so). And if you do this and the components are still focusable, then the whole thing breaks down if a component gains focus -- not good.
Better (as per comments) is to use Key Bindings which don't require focus to work if you use the correct InputMap. Note that key bindings is how Swing itself traps keystrokes for components, so using this would follow with the Swing general structure and contracts. The problem with Key Bindings is that you have to bind each key that you wish to trap, but you can use for loops to assist with this.
Another solution is to use a KeyEventDispatcher to the keyboard focus manager:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
// code goes here
return false;
}
});
Example using Key Bindings:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class KeyboardFun extends JPanel {
private InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
private ActionMap actionMap = getActionMap();
public KeyboardFun() {
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new GridLayout(0, 8, 3, 3));
for (char c = 'A'; c <= 'Z'; c++) {
final String text = String.valueOf(c);
JButton button = new JButton(text);
button.addActionListener(e -> {System.out.println("Key pressed: " + text);});
add(button);
setBinding(c, button);
}
}
private void setBinding(char c, final JButton button) {
KeyStroke keyStroke = KeyStroke.getKeyStroke(Character.toLowerCase(c));
inputMap.put(keyStroke, keyStroke.toString());
actionMap.put(keyStroke.toString(), new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
button.doClick();
}
});
}
private static void createAndShowGui() {
KeyboardFun mainPanel = new KeyboardFun();
JFrame frame = new JFrame("KeyboardFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
You must focus the object that you add listener, try add listener to "myJFrame". You can't focus JPanel.
Your JPanel is probably isn't focusable at start and your JButton gets Focus.
So you can also add this codes to "myJPanel" :
setFocusable(true);
requestFocusInWindow();

Java: Check if JButton is Pressed inside Frame MousePressListener

I have JFrame that has a button inside it. When the user click anywhere on the frame, I want to check if the button was pressed or clicked before it.
For example if the user the click on the frame without clicking the button first it should say "button not pressed" but if the user click the button then press anywhere on the frame then it should say "button is pressed".
My Code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test1
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Test 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
frame.add(panel,BorderLayout.NORTH);
final JButton btnRectangle = new JButton("Rectangle");
panel.add(btnRectangle);
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
int x = event.getX() ;
int y = event.getY() ;
System.out.println("you have press the mouse at X : " + x + " and Y : " + y);
if(btnRectangle.getModel().isSelected())
System.out.println("the button is pressed");
else
System.out.println("the button is NOT pressed");
}
public void mouseReleased(MouseEvent event){}
public void mouseClicked(MouseEvent event){}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
}
MousePressListener mListener = new MousePressListener();
frame.addMouseListener(mListener);
frame.setVisible(true);
}
}
As you can see I tried to check if the button was clicked inside the JFrame MousePressed Listener. But with no success. I also look at the question:
How can I check that JButton is pressed? If the isEnable() is not work?
But Can't seem to get anywhere, please help
It's done do following steps,
public class Test2
{
static boolean isPressed = false;
public static void main(String[] args)
{
.....
btnRectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isPressed = true;
}
});
.....
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
if(!isPressed){
System.out.println("the button is NOT pressed");
}else{
System.out.println("the button is pressed");
}
.....
}
}
}
}
See output,

Update a JPopupMenu menu items while it is open

In my UI i have a JPopMenu with values as ,
for e.g A,B,C
The scenario is,
I opened the JPopupMenu and kept it open.
At back end with a timer running , it updates the content B to some other alphabet at frequent interval.
3.I want the JPopupMenu to get updated while it is kept open.
In current behavior if i close and open JPopupMenu the updated value shows up.
I tried repaint()but it doesn't do anything.
What is the best way to do this?? Am new to swings please help.
Menu items can change their content at run time just fine. Without seeing your code it's hard to tell what you're doing wrong, but here's a working example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class PopupTest {
private static final String[] messages = {
"You are today's 1000th user!",
"You have won an internet!",
"Claim your prize!"
};
private PopupTest() {
JFrame frame = new JFrame("You have won");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lbl = new JLabel("Check your prize!");
frame.setLocationByPlatform(true);
frame.add(lbl);
frame.pack();
final JPopupMenu menu = new JPopupMenu();
final JMenuItem item = new JMenuItem(messages[0]);
menu.add(item);
menu.add(new JMenuItem("Another item that does not work"));
final Timer timer = new Timer(1000, new ActionListener() {
int count;
#Override
public void actionPerformed(ActionEvent e) {
count++;
count %= messages.length;
item.setText(messages[count]);
}
});
menu.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
timer.stop();
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
timer.stop();
}
});
lbl.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
#Override
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
menu.show(e.getComponent(), e.getX(), e.getY());
timer.start();
}
}
});
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new PopupTest();
}
});
}
}
Try to use .revalidate() with .repaint() it might help.
The docs suggest that the revalidate method is called every time something like size changes and manually calling it with repaint seems to solve problems like these.

Clear JTextField Contents on Click

So I've built a very basic Web browser - I'm trying desperately to remove the contents of the address bar when a user clicks on it (JTextField) this appears with some text in as default. Any advice is appreciated.
Have a great day!
MY CODE
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Web_Browser extends JFrame {
private final JTextField addressBar;
private final JEditorPane display;
// Constructor
public Web_Browser() {
super("Web Browser");
addressBar = new JTextField("Click & Type Web Address e.g. http://www.google.com");
addressBar.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
loadGo(event.getActionCommand());
}
}
);
add(addressBar, BorderLayout.NORTH);
display = new JEditorPane();
display.setEditable(false);
display.addHyperlinkListener(
new HyperlinkListener(){
#Override
public void hyperlinkUpdate(HyperlinkEvent event){
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED){
loadGo(event.getURL().toString());
}
}
}
);
add(new JScrollPane(display), BorderLayout.CENTER);
setSize(500,300);
setVisible(true);
}
// loadGo to sisplay on the screen
private void loadGo(String userText) {
try{
display.setPage(userText);
addressBar.setText(userText);
}catch(IOException e){
System.out.println("Invalid URL, try again");
}
}
}
Use a FocusListener. On focusGained, select all.
addressBar.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComponent = (JTextComponent) e.getSource();
textComponent.selectAll();
}
});
For example:
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
#SuppressWarnings("serial")
public class FocusExample extends JPanel {
private static final int TF_COUNT = 5;
private JTextField[] textFields = new JTextField[TF_COUNT];
public FocusExample() {
for (int i = 0; i < textFields.length; i++) {
textFields[i] = new JTextField("Foo " + (i + 1), 10);
textFields[i].addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
JTextComponent textComponent = (JTextComponent) e.getSource();
textComponent.selectAll();
}
});
add(textFields[i]);
}
}
private static void createAndShowGui() {
FocusExample mainPanel = new FocusExample();
JFrame frame = new JFrame("FocusExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This gives the user the option of leaving the previous text in place, of adding to the previous text, or of simply over-writing it by typing.
new JTextField("Click & Type Web Address e.g. http://www.google.com");
Maybe you want the Text Prompt, which doesn't actually store any text in the text field. It just gives the user a hint what the text field is for.
This is beneficial so that you don't generate DocumentEvents etc., since you are not actually changing the Document.
Add a mouseListener instead of your actionListener method.
addressBar.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
addressBar.setText("");
}

Changing value of boolean when mouse cursor hovers over a JButton

I have a button that will change from black to gray when you hover over, I do this with setRolloverIcon(ImageIcon);. Is there any easy way to make a boolean equals to true while the mouse cursor hovers over the JButton or would I have to use a MouseMotionListener to check the position of the mouse cursor?
Is there any easy way to make a boolean equals to true while the mouse
cursor hovers over the JButton
you can to add ChangeListener to ButtonModel, e.g.
JButton.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover()) {
//do something with Boolean variable
} else {
}
}
});
This is an example of using the ButtonModel:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestButtons {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton("Hello");
button.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (button.getModel().isRollover()) {
button.setText("World");
} else {
button.setText("Hello");
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButtons().createAndShowGUI();
}
});
}
}
Try this:
button.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
yourBoolean = true;
}
}
good luck

Categories

Resources