通過說動態圖我的意思是用戶可以在屏幕上拖動Vertices,然後再移除等等。繪製動態圖。
我被困在這一點,我想繪製更多的一個頂點,並試圖避免使JVM在圖形變化時重新繪製整個圖形。
我必須讓它繪製整個圖表還是有另一種方法來做到這一點?
這裏是我的代碼:
class GraphPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Vector<Vertex> V=new Vector<Vertex>();
private Vertex v;
private int R = 20;
public GraphPanel() {
V.add(new Vertex(70,70));
V.add(new Vertex(10,50));
paintGraph();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
for (int i=0;i<V.size();i++) {
if ((V.get(i).getX()<=e.getX() && V.get(i).getX()+R>=e.getX()) && (V.get(i).getY()<=e.getY() && V.get(i).getY()+R>=e.getY())) {
v=V.get(i);
moveVertex(e.getX(),e.getY());
v.changeState();
}
}
}
public void mouseReleased(MouseEvent e) {
v.changeState();
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
if (v.isPressed()) moveVertex(e.getX(),e.getY());
}
});
}
private void paintGraph() {
int OFFSET = 1;
for (int i=0;i<V.size();i++) {
v=V.get(i);
repaint(v.getX(),v.getY(),R+OFFSET,R+OFFSET);
}
}
private void moveVertex(int x, int y) {
int OFFSET = 1;
if ((v.getX()!=x) || (v.getY()!=y)) {
repaint(v.getX(),v.getY(),R+OFFSET,R+OFFSET);
v.setLocation(x-10, y-10);
repaint(v.getX(),v.getY(),R+OFFSET,R+OFFSET);
}
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (v!=null) {
g.setColor(Color.RED);
g.fillOval(v.getX(),v.getY(),R,R);
g.setColor(Color.BLACK);
g.drawOval(v.getX(),v.getY(),R,R);
}
}
}
public class Vertex {
private int x,y;
boolean isPressed;
Vertex(int x0,int y0) {x=x0;y=y0;isPressed=false;}
public void setLocation(int x0,int y0) {x=x0;y=y0;}
public int getX() {return x;}
public int getY() {return y;}
public boolean isPressed() {return isPressed;}
public boolean changeState() {return isPressed=!isPressed;}
}
public class Tester {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GraphPanel());
f.pack();
f.setVisible(true);
}
}
繪製圖表爲什麼不依賴像JFreeChart這樣的第三方庫? – Acn 2012-01-06 07:55:20
因爲我想讓我的手髒:) – 2012-01-06 08:08:37
請學習java的命名約定並堅持給他們 – kleopatra 2012-01-06 09:27:00