java拖放以在JPanel上移动JTextArea
我希望能够单击一个JTextArea
并将其拖动到我的JPanel
周围。我不确定这样做的方法。我要做的是改变JTextArea
的x,y坐标,当它被拖动时,我不会把一个JTextArea
拖到另一个上面或下面。就在屏幕上,类似于在Microsoft PowerPoint之类的程序中移动文本框
我能想到的唯一方法是使用MouseListener
,但我想知道除了检测JTextArea
上的悬停/按下/拖动之外,是否还有更简单的方法来实现它。有没有关于我如何开始的想法
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Canvas canvas = new Canvas();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(canvas);
JMenuBar menubar = new JMenuBar();
JMenuItem newTextBox = new JMenuItem("New Text Box");
newTextBox.setMnemonic(KeyEvent.VK_E);
newTextBox.setToolTipText("Exit application");
newTextBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
canvas.addTextBox();
}
});
menubar.add(newTextBox);
setJMenuBar(menubar);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Canvas extends JPanel {
JTextArea commentTextArea = new JTextArea(10, 10);
public Canvas() {
this.setOpaque(true);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
public void addTextBox() {
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
commentTextArea.setLocation(0, 0);
this.add(commentTextArea);
commentTextArea.setBounds(0, 0, 100, 100);
revalidate();
repaint();
}
class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
}
# 1 楼答案
你真的不想在
JTextComponent
上尝试和“拖动”,它们已经启用了允许用户点击和拖动以突出显示文本的功能,你真的不想在这个范围内竞争相反,您希望在组件周围定义一个“热区”区域,该区域允许您在某些位置“高亮显示”组件,并允许用户通过它拖动组件
例如
这将设置一个简单的代理组件,充当热区管理器,检测鼠标进出,并根据光标在其中的位置更新光标,但不会中断组件的正常操作
现在,这个例子没有拖拽,对不起,你有很多其他的例子应该可以让你越过这条线,但是,你可以简单地向代理添加一个
MouseListener
/MouseMoitionListener
来检测用户何时拖拽,但是你需要向它添加更多的功能来确定拖拽的实际含义(调整大小或移动);)