Originariamente inviato da cribcaged
allora ho provato a fare una classe Arrow che estende JComponent e ha un metodo:
public void paintComponent(Graphics g){
g.drawLine(...);
}
e poi
mio.getContentPane().add(new Arrow());
ma anche questo non funziona...
Perché probabilmente non hai capito come funziona il "rendering" nelle interfacce utente basate su "eventi".
Osserva e prova attentamente il seguente codice che ho scritto (nota, Java 5 o superiore):
codice:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class LinesTestFrame extends JFrame
{
private LinesComponent lines;
private JButton button;
public LinesTestFrame ()
{
super ("Lines Test");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setSize (300, 300);
lines = new LinesComponent ();
add (lines, BorderLayout.CENTER);
button = new JButton ("Aggiungi una linea casuale");
add (button, BorderLayout.SOUTH);
button.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
Point start = new Point ((int) (Math.random () * 200), (int) (Math.random () * 200));
Point end = new Point ((int) (Math.random () * 200), (int) (Math.random () * 200));
Line l = new Line (start, end, Color.RED);
lines.addLine (l);
}
});
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
LinesTestFrame f = new LinesTestFrame ();
f.setVisible (true);
}
});
}
}
class Line
{
private Point start;
private Point end;
private Color color;
public Line (Point start, Point end, Color color)
{
this.start = start;
this.end = end;
this.color = color;
}
public Point getStartPoint () { return start; }
public Point getEndPoint () { return end; }
public Color getColor () { return color; }
}
class LinesComponent extends JComponent
{
private ArrayList<Line> lines;
public LinesComponent ()
{
lines = new ArrayList<Line> ();
}
public void addLine (Line l)
{
lines.add (l);
repaint ();
}
public void paintComponent (Graphics g)
{
super.paintComponent (g);
for (Line l : lines)
{
g.setColor (l.getColor ());
g.drawLine (l.getStartPoint ().x, l.getStartPoint ().y,
l.getEndPoint ().x, l.getEndPoint ().y);
}
}
}
javac LinesTestFrame.java
poi
java LinesTestFrame