Reputation: 3485
I have searched quite bit to find a solution to my problem with no luck. I would have thought there to be a simple solution. I have the following code where I find a number of points stored in an ArrayList and would like to drap a shape (Doesn't matter what at this stage, a rectangle will do) at each point given in the ArrayList. The code is as follows:
public static void main(String[] args){
image = null;
try {
// Read from a file
File file = new File("box.jpg");
image = ImageIO.read(file);
} catch (IOException e) {
System.out.print("LAAAAMMME!!!!");
}
ImagePanel panel = new ImagePanel(image); //Custom JPanel to show a background image
panel.setPreferredSize(new Dimension(500, 500));
JFrame frame = new JFrame("Find the Squares");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(panel);
frame.validate();
frame.setVisible(true);
frame.pack();
ArrayList<Point> points = getCenterPoint(floatarray);
for(int x = 0 ; x < points.size(); x++){
//Here I guess is where each point is created and drawn.
}
}
Any suggestions?
Upvotes: 1
Views: 216
Reputation: 12696
Add an attribute List<Point> list
to ImagePanel
.
Override paintComponent(g)
in ImagePanel
. Use the data in the attribute list
to draw.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(...);
}
Send the list from JFrame
to ImagePanel
.
You might have to call frame.setLayout(new FlowLayout())
after constructing the frame.
Upvotes: 1
Reputation: 30855
class MyTest{
public static void main(String[] args){
image = null;
try {
// Read from a file
File file = new File("box.jpg");
image = ImageIO.read(file);
} catch (IOException e) {
System.out.print("LAAAAMMME!!!!");
}
ImagePanel panel = new ImagePanel(image); //Custom JPanel to show a background image
panel.setPreferredSize(new Dimension(500, 500));
JFrame frame = new JFrame("Find the Squares");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(panel);
frame.add(new MainPanel(Color.Red));
frame.validate();
frame.setVisible(true);
frame.pack();
/*ArrayList<Point> points = getCenterPoint(floatarray);
for(int x = 0 ; x < points.size(); x++){
//Here I guess is where each point is created and drawn.
}*/
}
private class MainPanel extends JPanel {
Color color;
public MainPanel(Color color) {
this.color = color;
}
public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(color);
//g.drawRect(startx,starty,endx,endy); // here you can drawRect as per your value
}
}
}
check this site
you need to pass the co-ordinate to the MainPanel class so you can draw the shape whatever you want to draw on panel.
Upvotes: 1