I don't want to create anymore JLabel object. I want to use addMouseListener because this way too pratice. But If I use this mouse listener doesn't work. Why?
Working code:
JLabel lb = new JLabel("Label 1");
lb.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.isShiftDown()){
System.out.println("Click");
}
}
});
Doesn't work:
add(new JLabel("Label1").addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.isShiftDown()){
System.out.println("Click triggered");
}
}
}));
addMouseListener(...)
Returns void therefore you cannot use the result as an argument for an other method call.
Related
i am constructing a word processor program as an assignment for my Java class in school and i am having a really hard time getting the popupmenu to work when i right click on my text area. I have already constructed the popup menu and have my textarea listening to my popuplistener and i have overridden the mouse pressed and mouse released functions with
class popupframe extends JFrame{
JMenuItem copy;
JMenuItem paste;
JTextArea textarea = new JTextArea();
JPopupMenu pop;
popupframe(){
Container cpane = getContentPane();
setSize(300 , 300);
setLocation(300, 300);
setTitle("Test");
JPopupMenu pop = new JPopupMenu();
copy = new JMenuItem("copy");
paste = new JMenuItem("paste");
textarea = new JTextArea("something goes here", 5, 5);
pop.add(copy);
pop.add(paste);
PopupListener popuplistener = new PopupListener();
textarea.addMouseListener(popuplistener);
}
class PopupListener extends MouseAdapter{
public void MousePressed(MouseEvent e){
popit(e);
}
public void MouseReleased(MouseEvent e){
popit(e);
}
private void popit(MouseEvent e){
if(e.isPopupTrigger()){
pop.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
I cannot see why it is not working but perhaps i am missing something crucial, please help!! much appreciated
Add the #Override annotation to the methods you think your are overriding...
class PopupListener extends MouseAdapter {
#Override
public void MousePressed(MouseEvent e) {
System.out.println("Pressed");
popit(e);
}
#Override
public void MouseReleased(MouseEvent e) {
System.out.println("Pressed");
popit(e);
}
You will now find that this fails to compile, but why? Because Java is case sensitive, and by convention, method names start with a lower case character
You'll find that something like...
class PopupListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
popit(e);
}
#Override
public void mouseReleased(MouseEvent e) {
popit(e);
}
#Override
public void mouseClicked(MouseEvent e) {
popit(e);
}
private void popit(MouseEvent e) {
if (e.isPopupTrigger()) {
pop.show(e.getComponent(), e.getX(), e.getY());
}
}
}
will work better. But having said that, you'll generally find
textarea.setComponentPopupMenu(pop);
significantly easier and less error prone (and it won't cause a NullPointerException like your example code will.
addItem = new JButton("Add");
gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weightx = 1.0;
panel.add(addItem, gc);
Am I able to make it into something like that:
addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
Instead of this I would want that button, but I have no idea what does that addItem do, since it does not let me to add a name there.
Is there a way how I can do this without modifying the 4 rows of code given at the beginning of the question?
what you can do is to add ActionListener to the button click or if you want you can add MouseListener , actually it depends on what you want to do
addItem.addActionListener(new ActtionListener() {...});
Code using an inner class instead of EventHandler.
addItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something
}
});
you can get more information on this in java official website.
Refer: http://docs.oracle.com/javase/7/docs/api/java/beans/EventHandler.html
if you add just the mouse listener you will not get the 'press' event if using keyboard. So, if your requirement is strictly bound to mouse press then use below snippet :)
addItem.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
// do something
}
#Override
public void mousePressed(MouseEvent e) {
// do something
}
#Override
public void mouseExited(MouseEvent e) {
// do something
}
#Override
public void mouseEntered(MouseEvent e) {
// do something
}
#Override
public void mouseClicked(MouseEvent e) {
// do something
}
});
for(int k=0;k< dtm.getRowCount();k++) //dtm is object of default table model
{
if(String.valueOf(dtm.getValueAt(k,1)).equalsIgnoreCase("Today") && check==0 )
{
cnt++;
JLabel jp=new JLabel();
panel.add(jp);
panel.setLayout(null);
if(cnt<=12)
{
jp.setBounds(j,500,100,100);
j=j+115;
jp.addMouseListener(this);
}
else
{
j=j-115;
jp.setBounds(j,400,100,100);
}
String b="<html><body text=#FDFA0B>"+String.valueOf(dtm.getValueAt(k,0))+"'s Birthday";
jp.setText(b);
jp.setFont(new java.awt.Font("comicbd",Font.ITALIC+Font.BOLD, 14));
}
}
It will not work mouselister only apply for last placed Label...
I want to apply mouse listener for all label how can I do that ..
please help me ....
Without SSCCE I can tell you that you're adding listener on 3 conditions:
String.valueOf(dtm.getValueAt(k,1)).equalsIgnoreCase("Today")
check == 0
and if(cnt<=12)
Other JLabels (that don't pass these conditions) haven't assigned your listener.
Make sure that you're clicking correct labels.
Or move jp.addMouseListener(this); just after JLabel creation (if you want to add listener to all your JLabels).
You certainly can add the same MouseListener to multiple components - here's an example in it's simplest form:
MouseListener ml = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {System.out.println("Released!");}
#Override
public void mousePressed(MouseEvent e) {System.out.println("Pressed!");}
#Override
public void mouseExited(MouseEvent e) {System.out.println("Exited!");}
#Override
public void mouseEntered(MouseEvent e) {System.out.println("Entered!");}
#Override
public void mouseClicked(MouseEvent e) {System.out.println("Clicked!");}
};
JLabel j1 = new JLabel("Label1");
j1.addMouseListener(ml);
JLabel j2 = new JLabel("Label2");
j2.addMouseListener(ml);
BUT according to your code, you're messing with a JTable - and JTable's act differently than you're thinking. The labels you're trying to edit are actually part of a TableCellEditor. The JTable uses the single TableCellEditor (read: single JLabel) to display every cell in the JTable. This is why you're only seeing the Listener applied to the last cell (because that's the only the last cell has a full component any more - the rest are just ghosts of where the component was applied before).
The good news is you can add a MouseListener to the JTable, and obtain information from there:
final JTable table = new JTable();
MouseListener ml = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
};
table.addMouseListener(ml);
One Option is to add another inner class:
class MListener extends MouseAdapter{
public void mouseReleased(MouseEvent e) {}
//other mouse evetns
}
then rather then:
jp.addmousListener(this);
do:
jp.addMouseListener(new MListener());
I'm developing a Swing based application in which I want to add JToolBar with images in JButton but it's not looking good. JToolBar is having some dots at the starting part.
How can I get rid of the dots?
Two things:
The "dots" you describe are probably due to the JToolbar being floatable by default. If you wish to disable this you can call setFloatable(false).
Here's a utility method I use to decorate JButtons prior to adding them to JToolBars (or JPanels, etc):
decorateButton(AbstractButton)
public static void decorateButton(final AbstractButton button) {
button.putClientProperty("hideActionText", Boolean.TRUE);
button.setBorder(BorderFactory.createEmptyBorder());
button.setBackground(null);
button.setOpaque(true);
button.setPreferredSize(BUTTON_SIZE);
button.setMaximumSize(BUTTON_SIZE);
button.setMinimumSize(BUTTON_SIZE);
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
button.setBackground(COLOR_BUTTON_MOUSEOVER);
}
#Override
public void mousePressed(MouseEvent e) {
button.setBackground(COLOR_BUTTON_PRESSED);
}
#Override
public void mouseEntered(MouseEvent e) {
button.setBorder(button.isEnabled() ? BORDER_BUTTON_MOUSEOVER_ENABLED : BORDER_BUTTON_MOUSEOVER_DISABLED);
button.setBackground(COLOR_BUTTON_MOUSEOVER);
}
#Override
public void mouseExited(MouseEvent e) {
button.setBorder(BorderFactory.createEmptyBorder());
button.setBackground(null);
}
});
}
I want to have a clickable icon (an ImageIcon object) inside a JLabel. How can I add a MouseListener or any ActionListener just to that Icon. Is there any other way to know if the icon has been clicked? I use the setIcon() method for the JLabel to set its icon.
Thanks.
You could have two separate JLabel inside a container, the first with text, the second with just the icon, and add a mouse listener to the icon JLabel.
This method is very hacky but worked for me.
JLabel.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
try {
Robot robot = new Robot();
if(JLabel.getBounds().contains(me.getPoint()) && !robot.getPixelColor(me.getXOnScreen(),me.getYOnScreen()).equals(page.getBackground())){
//Do action here
}
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
you can use this code to solving your problem:
public class Test extends JFrame {
private JLabel label;
ImageIcon icon = new ImageIcon("example.gif");
public Test(){
label = new JLabel(icon);
label.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
//for example
JOptionPane.showMessageDialog(null, "Hello");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
}