为了好玩,我一直致力于开发这个简单的股票图表GUI,它从YahooFinance中获取图表并将其显示在tabbed-Jpanel中。我已经能够获得用户定义的股票和所有股票的标签。但是,我开发了一些按钮,允许人们查询不同的图表方面(铃声带,移动平均线等),并希望能够使用此更新图表“重绘”面板。
问题:我不确定如何通过以下方法访问我创建的各个面板。我需要能够选择一个面板(比如下面i = 1时创建的panel1)并在ActionListener中更新它。我真的只是想知道Java如何在循环中定义这些面板,以便我以后可以访问它们并重新绘制标签!干杯。
public static void urlstock(String options,final String[] s, final JFrame f,final
JTabbedPane tpane) throws IOException{
for(int i=0;i<s.length;i++){
String path = "http://chart.finance.yahoo.com/z?s="+s[i]+options;
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel=new JPanel();
tpane.addTab(s[i],null, panel);
panel.add(label);
}
所以我尝试了按钮按下提示,但它不起作用,因为它无法将panel
识别为变量,原因超出了我的理解范围:
public void actionPerformed(ActionEvent e)
{ //Execute when button is pressed
System.out.println("MAButton");
tpane.getComponentAt(1);
tpane.remove(panel);
//Container.remove();
String path = "http://chart.finance.yahoo.com/z?s=GOOG&t=7m&z=l&q=l&a=ss,sfs";
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
JLabel label = new JLabel(new ImageIcon(image));
JPanel panel=new JPanel();
tpane.setComponentAt(1,panel);
panel.add(label);
}
答案 0 :(得分:1)
s[i]
)JTabbedPane#indexOfTab(String)
JTabbedPane#getComponentAt(int)
)Container#removeAll()
使用示例更新
public class TestTabPane {
public static void main(String[] args) {
new TestTabPane();
}
public TestTabPane() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTabbedPane tabPane = new JTabbedPane();
JPanel panel = new JPanel();
JButton updateButton = new JButton("Update me");
panel.add(updateButton);
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int indexOfTab = tabPane.indexOfTab("Testing");
JPanel panel = (JPanel) tabPane.getComponentAt(indexOfTab);
panel.removeAll();
panel.add(new JLabel("I've begin updated"));
panel.repaint();
}
});
tabPane.addTab("Testing", panel);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(tabPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}