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);
}
基本上,我有这个代码。它引用一个名为Circle
的类,该类计算一个圆的外边缘上的一些点,并使用paintComponent
来绘制它们。在这个类中,有一个叫做getImage
的方法,它采用paintComponent
方法绘制的内容并将其放入BufferedImage中。如何使此ActionListener完全重新绘制JFrame?
public BufferedImage getImage() {
BufferedImage hello = new BufferedImage(805, 805, BufferedImage.TYPE_INT_ARGB);
Graphics g = hello.getGraphics();
paintComponent(g);
return hello;
}
像这样。
我遇到的问题是我无法找到一种方法来完全重新绘制JFrame
。我试着用removeAll()
清除JFrame
的actionPerformed
方法中,然后完全一遍设立框架(add
所有组件,pack
,setSize
,setTitle
等),然后repaint
,revalidate
,或者只是validate
它。
如果我只是把它add
的图像,然后validate
它,我可以看到正在更新的图像,但它刚刚在JFrame
年底上涨了(就像我期待它使用FlowLayout
),但那不是我需要的行为。它只是表明它有点工作。
我的问题是:当用户更改JComboBox
中的选项时,如何使其重新绘制JFrame
?
为了更好地帮助越早,张贴[SSCCE](http://sscce.org /)。 –