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();
}
}
}
你在框架內創建新框架,而不是最好的解決方案,將Jpanel傳入getGraph方法也不起作用 –
使您的'JPanel graphPanel'成爲類成員變量,以便您可以保留對其的引用。然後讓getGraph()返回一個JPanel,並在你的actionePerformed中執行'graphPanel = b.getGraph();'。然後打包()你的框架。 – geneSummons