从不同 class 到 GUI class 的条形图
Bar Chart from different class in to GUI class
我有带有 JPanel 和 JButton 的 Gui class。单击按钮后,我想在我的 JPanel 中显示图形。该图在不同 class 中。有人可以帮我做这个吗?
GUI CLASS:
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();
}
}
}
更改您的 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() return 成为 JPanel,然后您可以将面板放在现有框架中而不是更新整个框架。
我有带有 JPanel 和 JButton 的 Gui class。单击按钮后,我想在我的 JPanel 中显示图形。该图在不同 class 中。有人可以帮我做这个吗?
GUI CLASS:
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();
}
}
}
更改您的 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() return 成为 JPanel,然后您可以将面板放在现有框架中而不是更新整个框架。