我有這個問題困擾了我好幾天。我正在製作一個特殊的繪畫程序。我製作了一個JPanel,並添加了使用paint(..)方法繪製的自定義jComponents。 問題是,無論何時調整窗口大小,所有添加的組件都「消失」(或者只是不畫),所以我最終得到了一個空框架。調整添加的塗漆組件和奇怪的揮杆行爲
另外我注意到使用這種方法時擺動的一些奇怪的行爲。我已經向描述這個問題的代碼添加了評論。
package simple;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class SimpleFrame extends JFrame {
JPanel paintArea;
SimpleCanvas c1;
SimpleCanvas c2;
ArrayList<SimpleCanvas> list;
public static void main(String[] args) {
SimpleFrame frame = new SimpleFrame();
}
public SimpleFrame() {
super("Test");
setSize(600,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//The panel to which my SimpleCanvas objects are added
paintArea = new JPanel();
paintArea.setPreferredSize(new Dimension(600, 500));
paintArea.addMouseListener(new paintAreaMouseEvents());
getContentPane().add(paintArea, BorderLayout.CENTER);
setVisible(true);
paintArea.setVisible(true);
//A list to hold all the objects together
list = new ArrayList<SimpleCanvas>(10);
//The same as in class paintAreaMouseEvent, but doesnt work
SimpleCanvas c = new SimpleCanvas();
c.setBounds(60, 100, 100, 50);
list.add(c);
paintArea.add(list.get(list.size() - 1));
paintArea.repaint();
}
//When you click the mouse, it makes an oval
class paintAreaMouseEvents extends MouseAdapter {
@Override
//This does work.
public void mouseClicked (MouseEvent me) {
SimpleCanvas c = new SimpleCanvas();
c.setBounds(me.getX() - 50, me.getY() - 25, 100, 50);
list.add(c);
paintArea.add(list.get(list.size() - 1));
paintArea.repaint();
}
}
}
這裏是SimpleCanvas類
package simple;
import java.awt.*;
import javax.swing.JComponent;
public class SimpleCanvas extends JComponent {
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLUE);
g.fillOval(0, 0, 100, 50);
}
}
謝謝:)
BTW:只想說這個網站是驚人的。我在使用Google的時候來過很多地方,現在我終於決定寫一個賬戶。
非常感謝您!我向jPanel的構造函數中添加了null參數,並解決了我所有的問題。 我想我現在必須學習如何使用LayoutManagers;) 再次,謝謝。 – Charnia 2012-01-17 20:22:37
@Charnia:不客氣。請參閱我的答案的附錄。 – 2012-01-17 22:39:57
感謝您的提示,我一定會牢記在心。問題是我正在編寫一個程序,該程序還允許您通過將另一個mouseEventHandler添加到自定義Canvas類來移動這些形狀,因此您建議的方法將無法工作。 – Charnia 2012-01-18 18:20:11