2017-03-16 39 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