I have code for drawing rectangles. He used to draw rectangles on JPanelto mark the borders of widgets. Here is the code first, after which I will explain my cq problem. question.
Firstly, I have a class ( WidgetDrawingPanel) that extends JPanel.
public WidgetDrawingPanel(int width, int height) {
widgets.add(new Widget(10,10,100,100, WidgetType.TextField));
widgets.add(new Widget(50,50,100,200, WidgetType.TextField));
this.width = width;
this.height = height;
this.setBackground(Color.BLUE);
addListener();
}
Below you will see a link ch. This CoordinateHolder, which contains the initial and current coordinates of the mouse.
private void addListener() {
this.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent arg0) {
ch.currentX = arg0.getX();
ch.currentY = arg0.getY();
System.out.println("dragging " + ch.currentX + ","+ch.currentY);
WidgetDrawingPanel.this.repaint();
}
});
this.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent event) {
ch.endX = event.getX();
ch.endY = event.getY();
try {
checkCoords();
} catch (OutsidePanelException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "drawn Outside Panel");
}
}
@Override
public void mousePressed(MouseEvent event) {
ch = new CoordinateHolder(event.getX(), event.getY());
}
});
}
, , paintComponent(Grapics). Widgets, Rects (x, y, w, h ), , . , , CoordinateHolder Widgets.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Paint");
g.setColor(Color.BLUE);
g.fillRect(0, 0, width, height);
g.setColor(Color.RED);
Graphics2D g2 = (Graphics2D)g;
g2.setStroke(new BasicStroke(3));
for (Widget w : widgets) {
g.drawRect(w.getX(), w.getY(), w.getW(), w.getH());
}
if (ch != null)
g.drawRect(ch.startX, ch.startY, ch.currentX - ch.startX, ch.currentY - ch.startY);
}
, , , JPanel , , , 10 ? , , ( , painComponent(Graphics)).
cq.
, , ?
Drag JFrame Java, , , , . , , inperformant, ? , ?