Reputation: 185
private static final long serialVersionUID = 1L;
String[] options = {"1","2","4","8","16","20","40","100","400"} ;
int[] optionsNum = {1,2,4,8,16,20,40,100,400};
JComboBox<String> box = new JComboBox<>(options);
JLabel prompt = new JLabel("How complex do you want the circle to be?");
ImageIcon image;
Circle p = new Circle(1);
int boxindex = 0;
public CircleDrawer(){
image = new ImageIcon(p.getImage());
box.setSelectedIndex(boxindex);
setLayout(new FlowLayout());
add(new JLabel(image));
add(prompt);
add(box);
pack();
setSize(851, 950);
setTitle("Circle Drawer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
box.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == box){
boxindex = box.getSelectedIndex();
p.setComplexity(optionsNum[boxindex]);
image = new ImageIcon(p.getImage());
add(new JLabel(image));
validate();
}
}
public static void main(String[] args) {
CircleDrawer f = new CircleDrawer();
f.setVisible(true);
}
Basically, I have this code. It references a class called Circle
, which calculates some points on the outer edge of a circle and draws them using a paintComponent
. In this class, there is a method called getImage
, which takes what the paintComponent
method drew and puts it into a BufferedImage.
public BufferedImage getImage() {
BufferedImage hello = new BufferedImage(805, 805, BufferedImage.TYPE_INT_ARGB);
Graphics g = hello.getGraphics();
paintComponent( g );
return hello;
}
Like so.
The problem I'm running into is that I can't find a way for it to completely re-draw the JFrame
. I've tried clearing the JFrame
within the actionPerformed
method using removeAll()
and then COMPLETELY setting up the frame all over again (add
all of the components, pack
, setSize
, setTitle
, etc) and then repaint
, revalidate
, or just validate
it.
If I simply have it add
the image and then validate
it, I can see the image being updated, but it's just getting tacked on at the end of the JFrame
(just like I would expect it to using a FlowLayout
) but that's not the behavior I need. It just shows that it is sort of working.
My question is this: How do I make it re-draw the JFrame
when the user changes options inside of the JComboBox
?
Upvotes: 0
Views: 90
Reputation: 324118
Graphics g = hello.getGraphics();
paintComponent( g );
Don't use getGraphics() and never invoke paintComponent() directly. Swing will invoke the proper painting methods are required.
add(new JLabel(image));
validate();
When you add (remove) components from a visible GUI the general structure of the code is:
add(...);
revalidate(); // to invoke the layout manager
repaint(); to repaint the components
Upvotes: 2