2017-03-16 23 views
0

我有一個JPanel和JButton類。點擊按鈕時,我想在我的JPanel中顯示圖形。圖形是在不同的類。有人可以幫我做這個嗎?從GUI類到不同類的條形圖

GUI類:

public class Gui extends JFrame implements ActionListener{ 

    JButton showGraph; 

    public Gui() { 

    super("GUI"); 
    setSize(1200,600); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    showGraph = new JButton("SHOW GRAPH"); 
    JPanel mainPanel = new JPanel(); 
    add(mainPanel); 
    mainPanel.setLayout(new GridLayout(2,0,10,10)); 
    mainPanel.setBorder(new EmptyBorder(10,10,10,10)); 
    mainPanel.add(showGraph); 
    JPanel graphPanel = new JPanel(); 
    graphPanel.setBackground(Color.yellow); 
    mainPanel.add(graphPanel); 

    showGraph.addActionListener(this); 

    } 



public static void main (String[] args){ 
    new Gui().setVisible(true); 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == showGraph) { 
     SimpleBarChart b = new SimpleBarChart(); 
     b.getGraph(); 
    } 
} 
} 

回答

0

更改getGraph()方法取一個JFrame,並通過在this

public void getgraph(JFrame f) { 

//JFrame f = new JFrame(); 
f.setSize(400, 300); 
... as before ... 
} 

然後調用的actionPerformed

if (e.getSource() == showGraph) { 
    SimpleBarChart b = new SimpleBarChart(); 
    b.getGraph(this); 
} 

你不能有一個框架內的幀。另一個選擇是讓getGraph()返回一個JPanel,然後你可以把面板放在你現有的框架中,而不是更新整個框架。

+0

你在框架內創建新框架,而不是最好的解決方案,將Jpanel傳入getGraph方法也不起作用 –

+0

使您的'JPanel graphPanel'成爲類成員變量,以便您可以保留對其的引用。然後讓getGraph()返回一個JPanel,並在你的actionePerformed中執行'graphPanel = b.getGraph();'。然後打包()你的框架。 – geneSummons