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
Related
When clicking the arrow to open the popup on a JComboBox the overridden setPopupVisible is not called, see minimal example below. Am i just missing something here or doing something wrong? Any hints appreciated :)
The goal here is that i want to control its visibility behaviour, especially only hiding it under certain conditions, for example input checking (mind that the combobox is editable).
Using Java 8.
Building a Frame with a custom JComboBox:
import java.awt.Frame;
import javax.swing.BoxLayout;
public class Test {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));
MyComboBox combo = new MyComboBox();
combo.setEditable(true);
combo.addItem("bli");
combo.addItem("bla");
combo.addItem("blu");
combo.addItem("ble");
frame.add(combo);
frame.pack();
frame.setVisible(true);
}
}
The custom JComboBox:
import javax.swing.JComboBox;
public class MyComboBox extends JComboBox {
#Override
public void setPopupVisible(boolean v) {
if(!v) {
System.out.println("HIDING COMBOBOX");
super.setPopupVisible(v);
} else {
System.out.println("SHOWING COMBOBOX");
super.setPopupVisible(v);
}
}
}
In JComboBox setPopupVisible(boolean) API is NOT there to notify when the popup is opened/closed. It is there to programmatically show the popup or hide the popup.
If you want to be notified when the popup is opened/closed, you can use addPopupMenuListener() like in below code:
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.Frame;
public class Test {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setLayout(new BoxLayout(frame, BoxLayout.Y_AXIS));
MyComboBox combo = new MyComboBox();
combo.setEditable(true);
combo.addItem("bli");
combo.addItem("bla");
combo.addItem("blu");
combo.addItem("ble");
combo.addPopupMenuListener(new PopupMenuListener()
{
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
System.out.println("Popup Menu Will Become Visible");
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
System.out.println("Popup Menu Will Become Invisible");
}
#Override
public void popupMenuCanceled(PopupMenuEvent e)
{
System.out.println("Popup Menu Canceled");
}
});
frame.add(combo);
frame.pack();
frame.setVisible(true);
}
}
class MyComboBox extends JComboBox
{
#Override
public void setPopupVisible(boolean v) {
if(!v) {
System.out.println("HIDING COMBOBOX");
super.setPopupVisible(v);
} else {
System.out.println("SHOWING COMBOBOX");
super.setPopupVisible(v);
}
}
}
Inside the constructor:
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
//Do something
}
public void mouseReleased(MouseEvent e){
//Do something
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseMoved(MouseEvent evt) {
cursorX = evt.getX();
cursorY = evt.getY();
}
});
mouseMoved is running while I don't click / Press any mouse button.
But when I click or hold the mouse button the cursor position is no longer updated and mouseMoved doesn't get called
I was searching for a solution for hours please help me!
I tried to implement MouseListener and MouseMotionListener to the class but this didn't work too.
The simple answer is, there's a difference between the mouse been moved across the surface of your component when the button is held and when it's not. The system will identify these differences and call different functionality.
This is done by design, presumably to make it easier to manage the two scenarios, which can generate different results (i.e. Drag'n'Drop)
The following example is a simple demonstration. When you press the mouse button and move the mouse, mouseDragged will be called, otherwise mouseMoved will be called
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
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 {
public TestPane() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("Released");
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("Moved");
}
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
I don't know why is this happening to you, but you can use the same code inside mouseMoved(MouseEvent evt) inside mouseDragged(MouseEvent evt) of MouseMotionListener too, that is triggered when the mouse is moving and pressing at the same time.
If this not work, this means that MouseListener are taking priority over MouseMotionListener, and in this case I don't know what you can do.
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.
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("");
}
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.