我基本上試圖通過調用第二個組件的paint來將第一個組件的圖形傳遞給另一個組件,從而在另一個內部繪製JComponent。我想創建一個GUI編輯器,(重新發明輪子,我知道,它只是一個概念證明) 所以我有一個類擴展JPanel,我想從VectorControls中繪製組件。使用其圖形繪製控制另一個
到目前爲止,我在擴展的JPanel了這種方法:
@SuppressWarnings("serial")
public class Sketch extends JPanel {
private Vector<JComponent> controls = new Vector<JComponent>();
public Sketch() {
super();
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
}
public void addControl(JComponent c) {
Dimension d = new Dimension(100,50);
c.setPreferredSize(d);
c.setMinimumSize(d);
c.setMaximumSize(d);
controls.add(c);
this.repaint();
this.revalidate();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=controls.size()-1; i>=0; i--) {
JComponent c = controls.get(i);
c.paint(g);
}
}
}
我建立/安裝草圖面板是這樣的:
public GUIEditor() {
mainFrame = new JFrame("GUI EDITOR");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Sketch mainPanel = new Sketch();
mainPanel.setPreferredSize(new Dimension(640,480));
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
mainFrame.setLayout(gbl);
JPanel toolsPanel = new JPanel();
toolsPanel.setPreferredSize(new Dimension(160,480));
toolsPanel.setLayout(new GridLayout(0,1));
for(Control c : toolBoxItems) {
AbstractAction action = new ToolBoxButtonAction(mainPanel, c.type);
JButton b = new JButton(action);
b.setText(c.title);
toolsPanel.add(b);
}
gbc.gridx = 0;
gbc.gridy = 0;
gbl.setConstraints(mainPanel, gbc);
mainFrame.add(mainPanel);
gbc.gridx = 1;
gbc.gridy = 0;
gbl.setConstraints(toolsPanel, gbc);
mainFrame.add(toolsPanel);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
裏面ToolBoxButtonAction,基本上我這樣做:
public void actionPerformed(ActionEvent e) {
try {
sketch.addControl(control.newInstance());
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
}
但我寫這個,因爲它不工作。
有關如何實現此目的的任何想法?
是'Controls'類還是'ArrayList'?如果它是一個列表,它應該被聲明爲'controls'(小寫)以方便閱讀。 –
wchargin
2013-05-10 14:31:51
*它不起作用*發生了什麼? – johnchen902 2013-05-10 14:33:04
@ johnchen902它不工作,因爲我沒有看到任何東西繪製到我的JPanel – 2013-05-11 00:32:06