繁体   English   中英

如何使这个ActionListener完全重绘JFrame?

[英]How to make this ActionListener completely re-draw JFrame?

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的类,它计算Circle的外边缘上的一些点并使用paintComponent绘制它们。 在这个类中,有一个名为getImage的方法,它接受paintComponent方法绘制的内容并将其放入BufferedImage中。

public BufferedImage getImage() {

    BufferedImage hello = new BufferedImage(805, 805, BufferedImage.TYPE_INT_ARGB);
    Graphics g = hello.getGraphics();
    paintComponent( g );

    return hello;
}

像这样。

我遇到的问题是我无法找到完全重新绘制JFrame 我尝试使用removeAll()actionPerformed方法中清除JFrame ,然后再次完全设置框架( add所有组件, packsetSizesetTitle等),然后repaintrevalidate或只是validate它。

如果我只是让它add图像然后validate它,我可以看到图像正在更新,但它只是在JFrame结束时加入(就像我希望它使用FlowLayout )但这不是行为我需要。 它只是表明它有点工作。

我的问题是:当用户更改JComboBox内的选项时,如何重新绘制JFrame

Graphics g = hello.getGraphics();
paintComponent( g );

不要使用getGraphics(),也不要直接调用paintComponent()。 Swing会调用正确的绘画方法。

 add(new JLabel(image));
 validate();

从可见GUI添加(删除)组件时,代码的一般结构是:

add(...);
revalidate(); // to invoke the layout manager
repaint(); to repaint the components

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM