[英]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
所有組件, pack
, setSize
, setTitle
等),然后repaint
, revalidate
或只是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.