• Post Reply Bookmark Topic Watch Topic
  • New Topic

JPopupMenu is not diplaying to the right of the mouse click when i right click on a JCheckbox

 
Sri Palem
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please execute the below program and let me know why the popup menu is displaying correctly for a JButton component and not for a JCheckbox and right click on those components


import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;


public class SamplePopup extends JFrame{

private JPopupMenu spopup = new JPopupMenu();
private JButton sb = new JButton("Sample");
private JPanel pane = new JPanel(new FlowLayout());
private JCheckBox cbox = new JCheckBox("Sample checkbox");
private JLabel lb = new JLabel("New Text");

public SamplePopup(){

setSize(500, 500);
spopup.add(new JMenuItem("Black"));
spopup.add(new JMenuItem("Blue"));
spopup.add(new JMenuItem("Red"));

sb.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
Component c = e.getComponent();
if(e.isMetaDown() && !e.isPopupTrigger()){
spopup.show(sb, e.getX(), e.getY());
}
}
});
cbox.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e1){
Component c = e1.getComponent();
if(e1.isMetaDown() && !e1.isPopupTrigger()){
spopup.show(sb, e1.getX(), e1.getY());
}
}
});

pane.add(sb);
pane.add(cbox);
getContentPane().add(pane);
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
SamplePopup ap = new SamplePopup();
}

}

 
Rob Camick
Ranch Hand
Posts: 2699
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the "Code" tags when posting code so the code retains its original formatting.

That would be because you display the popup relative to the "sb" variable in both cases.

Instead of writing duplicate code do something like this to somplify your code.


See how much nicer and easy to read it is with the code tags.
 
Sri Palem
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Rob
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!