2013-12-15 90 views
0
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()清除JFrameactionPerformed方法中,然后完全一遍设立框架(add所有组件,packsetSizesetTitle等),然后repaintrevalidate,或者只是validate它。

如果我只是把它add的图像,然后validate它,我可以看到正在更新的图像,但它刚刚在JFrame年底上涨了(就像我期待它使用FlowLayout),但那不是我需要的行为。它只是表明它有点工作。

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

+0

为了更好地帮助越早,张贴[SSCCE](http://sscce.org /)。 –

回答

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

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

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

当您添加从可视GUI代码的一般结构(删除)成分:

​​3210
+0

感谢您的意见。除了getGraphics以外,我还需要什么? 在我看来,我不应该添加/删除组件,因为我正在用'image = new ImageIcon(p.getImage());'来更改该组件所在的变量,但是当我尝试'重新验证'/'repaint',什么都不会发生。 – tssguy123

+0

'除了getGraphics以外,我还使用了什么?' - 您的组件中有'setter'方法来更改组件的属性。然后在setter方法中调用revalidate()和repaint()。 '我不应该添加/删除组件' - 完全同意,但是你发布的代码表明你正在添加一个组件,所以我只是解释了正确的方法来做到这一点。 – camickr

+0

我很确定我必须使用'getGraphics'。除非有某种方法可以使'paintComponent'遵循布局,有人告诉我要做到这一点的唯一方法是绘制一个'BufferedImage',当我搜索如何做时,我被告知要使用'getGraphics'。我不能在'actionPerformed'方法内调用f.repaint(),只能调用'repaint()'。在这一点上我很困惑。哈哈。 – tssguy123