复合材料中的选择性菜单检测

时间:2012-12-23 10:17:34

标签: java swt contextmenu composite java-canvas

我想将一些对象添加到Composite对象中。对象可以有不同的形状(矩形,圆形,椭圆形或甚至奇怪的形状(由多边形表示)。所以我定义了这样的类:

public class Circle extends Canvas {
}

public class Rectangle extends Canvas {
}

...

我知道如何在Canvas中绘制以获得我想要的形状,但我也希望只有当用户在画布区域内单击鼠标时才会在每个画布上显示弹出菜单,所以如果我使用这些复合类中的代码:

Menu aSampleMenu = new Menu(this);

Circle circle = new Circle(parent, style);
circle.setMenu(aSampleMenu);

如果用户在画布内的任何位置单击鼠标右键,即使在形状区域外,也会出现菜单。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

查看下面的代码段。诀窍是首先定义Menu,然后仅将其设置为应允许菜单检测的那些Control

public class StackOverflow
{
    public static void main(String[] args)
    {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(2, true));

        Composite c1 = new Composite(shell, SWT.BORDER);
        c1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        Composite c2 = new Composite(shell, SWT.BORDER);
        c2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        Menu menu = new Menu(shell, SWT.POP_UP);
        MenuItem item = new MenuItem(menu, SWT.PUSH);
        item.setText("Popup");

        new Label(shell, SWT.BORDER).setText("No menu here");
        new Label(shell, SWT.BORDER).setText("No menu here");

        // Add menu only to c1 and c2, not to the shell and not to the labels
        c1.setMenu(menu);
        c2.setMenu(menu);

        shell.setSize(300, 300);
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }
}

以下是截图:

enter image description here

答案 1 :(得分:0)

一种解决方案是使用Region,但我仍然不知道它如何应用于圆形情况:

    Region region = new Region();
    region.add(new int[] {3, 3, 20, 20, 3, 20});

    Canvas c = new Canvas(this, SWT.NONE);
    c.setBounds(35, 35, 60, 60);
    c.setRegion(region);

    Menu menu = new Menu(this);
    c.setMenu(menu);

    MenuItem mntmProperties = new MenuItem(menu, SWT.NONE);
    mntmProperties.setText("Properties");

    MenuItem mntmDelete = new MenuItem(menu, SWT.NONE);
    mntmDelete.setText("Delete");
相关问题