그래서 JMenu 항목 "New Rectangle"을 클릭하고 화면 중앙에 도형을 추가하는 간단한 프로그램이 있습니다. 내 질문은 : 어떻게 창 주위를 클릭하고 드래그 할 수 있습니까? 나는 어떤 유형의 마우스 리스너가 필요할 것임을 알고 있지만 정확히 구현하는 방법을 모르겠습니다.클릭하여 드래그하여 JPanel에서 도형을 이동하는 방법
public class SimpleDraw {
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);
// Display the window.
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Squares squares = new Squares();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(squares);
JMenuBar menubar = new JMenuBar();
JMenu shapes = new JMenu("Shapes");
JMenuItem rectangleMenuItem = new JMenuItem("New Rectangle");
rectangleMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
squares.addSquare(10, 10, 100, 100);
}
});
shapes.add(rectangleMenuItem);
menubar.add(shapes);
setJMenuBar(menubar);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Squares extends JPanel {
private static final long serialVersionUID = 1L;
private List<Rectangle> squares = new ArrayList<Rectangle>();
public void addSquare(int x, int y, int width, int height) {
Rectangle rect = new Rectangle(getWidth()/2 - width/2, getHeight()
/2 - height/2, width, height);
squares.add(rect);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setOpaque(true);
this.setBackground(Color.WHITE);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle rect : squares) {
g2.draw(rect);
}
repaint();
}
}
AffineTransform을 사용하여 [이 답변] (http://stackoverflow.com/a)에서와 같이 Shape 객체를 변환하는 것이 하나의 방법입니다./22595225/522444). –
http://docs.oracle.com/javase/tutorial/uiswing/dnd/intro.html – DavidPostill
MouseListener 및 MouseMotionListener가 필요합니다. – MadProgrammer