这是我的代码......
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.*;
public class LineDrawing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createWindow();
}
});
}
private static void createWindow() {
JFrame mainFrame = new JFrame();
mainFrame.add(new myPanel());
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setBackground(Color.white);
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
}
class myPanel extends JPanel {
int startX;
int startY;
int endX;
int endY;
public myPanel() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
repaint(startX, startY, endX, endY);
}
@Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
repaint(startX, startY, endX, endY);
}
@Override
public void mouseClicked(MouseEvent e) {
startX = e.getX();
endX = startX;
startY = e.getY();
endY = startY;
repaint(startX, startY, endX, endY);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
endX = e.getX();
endY = e.getY();
repaint(startX, startY, endX, endY);
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(startX, startY, endX, endY);
repaint();
}
}
我正在尝试绘制多条线,同时保持前一条线仍然存在于屏幕(框架)上... 但是,当我再次点击时,前一行会被擦掉或擦除......
我正在设计一个图形分析应用程序(它将告诉输入的图形是否是同构的......
我的问题是我无法绘制多条线但只能绘制一条线......
答案 0 :(得分:2)
我的问题是我无法绘制多条线但只能绘制一条线......
它仅绘制1行,因为您只在paintComponent中绘制了1行。 请注意,图纸 不 是累积的。
CostofA.keys()
要绘制多条线条(如图形),您需要一个数据结构来保存每个图形的数据。然后你可以迭代它并从那里绘制多条线。
因此只保留一组情节protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(startX,startY,endX,endY); //this will draw only one line..
repaint(); //do not do this!
}
。您可以为Plot:
(startX, startY, endX, endY)
然后在显示面板中,保留一个绘图列表:
public class Plot
{
private int startX;
private int startY;
private int endX;
private int endY;
public Plot(int startX, int startY, int endX, int endY){
this.startX = startX;
this.startY = startY;
this.endX = endX ;
this.endY = endY ;
}
public void draw(Grpahics g){
g.setColor(Color.black);
g.drawLine(startX,startY,endX,endY);
}
}
最后,在您的class MyPanel extends JPanel
{
private ArrayList<Plot> plots;
public MyPanel(){
plots = new ArrayList<Plot>();
}
public void addPlot(int x1, int y1, int x2, int y2){
plots.add(new Plot(x1, y1, x2, y2))
}
//Invoke addPlot() in your mouseListener after you get startXY & endXY
//Invoke repaint() after addPlot()
//Don't have to do this: "repaint(startX,startY,endX,endY);"
}
:
paintComponent()
此外,您不应在@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
for(Plot p : plots)
p.draw(g); //Each plot will draw itself
}
内致电repaint()
。当您需要刷新屏幕时,可以在paintComponent()
之外拨打电话。