需求:在组件上单击右键,要有Copy和Paste的功能.
具体实现:
成功的方法:继承自java.awt.TextField
public class TextFieldLabel extends java.awt.TextField implements MouseListener, FocusListener{
...
...
public void setRightButtonEnable(boolean rightButtonEnable)
{
this.rightButtonEnable = rightButtonEnable;
if (rightButtonEnable == true) {
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
} else {
disableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
}
...
...
}
失败的方法:继承自javax.swing.JTextField
public class ScTextFieldLabelSwing extends javax.swing.JTextField implements MouseListener, FocusListener
{
....
....
public void setRightButtonEnable(boolean rightButtonEnable)
{
this.rightButtonEnable = rightButtonEnable;
if (rightButtonEnable == true) {
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
} else {
disableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
}
...
...
}
问题:同样的setRightButtonEnable方法在swing中为什么不好用.而在awt中可以使用,怎样解决呢?
以下是awt组件的截图
[UploadFile=test2_1188794696.jpg]
------解决方案--------------------
楼主如果只是问弹出菜单的话,参考一下下面:
import java.awt.event.*;
import javax.swing.*;
public class MenuTest
{
public static void main(String[] args)
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a sample menu bar.
*/
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle( "MenuTest ");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
Action cutAction = new TestAction( "Cut ");
Action copyAction = new TestAction( "Copy ");
Action pasteAction = new TestAction( "Paste ");
// demonstrate pop-ups
popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
add(panel);
JTextField field = new JTextField(20);
panel.add(field);
field.setComponentPopupMenu(popup);
}
public static final int DEFAULT_WIDTH = 300;