所以为了好玩,我一直在开发这个简单的股票图表GUI,它从YahooFinance获取图表并将它们显示到选项卡式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);
}
- 使用标签
- 的名称(
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);
}
});
}
}