我有一个JFrame根据您单击的MenuItem显示JPanels。它可以工作,但是现在我需要在将JPanel添加到框架中并显示该方法之后调用一个方法(因为我在该面板内使用JFreeChart,并且当JPanel可见时我必须调用chartPanel.repaint()):

this.getContentPane().add( myjpanel, BorderLayout.CENTER ); //this = JFrame
this.validate();
myjpanel.methodCalledOnceDisplayed();

看起来还好吗?确实显示了myjpanel吗?似乎不是:
public void methodCalledOnceDisplayed() {
    chartPanel.repaint()
}

这是行不通的(chartPanel.getChartRenderingInfo().getPlotInfo().getSubplotInfo(0)抛出IndexOutOfBoundsException)。这意味着在调用repaint时,JPanel不可见,我已经测试了以下内容:
public void methodCalledOnceDisplayed() {
    JOptionPane.showMessageDialog(null,"You should see myjpanel now");
    chartPanel.repaint()
}

现在它可以正常工作了,我在警报后面看到了myjpanel,正如预期的那样,chartPanel重新绘制,并且没有发生异常。

编辑:SSCCE(需要jfreechart和jcommon:http://www.jfree.org/jfreechart/download.html)

导入java.awt.BorderLayout;
导入java.awt.EventQueue;
导入java.awt.Font;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JOptionPane;
导入javax.swing.JPanel;
导入javax.swing.border.EmptyBorder;
导入org.jfree.chart.ChartMouseEvent;
导入org.jfree.chart.ChartMouseListener;
导入org.jfree.chart.JFreeChart;
导入org.jfree.chart.plot.CombinedDomainXYPlot;
导入org.jfree.chart.plot.PlotOrientation;
导入org.jfree.chart.plot.XYPlot;
导入org.jfree.chart.ChartPanel;
导入org.jfree.data.time.TimeSeries;
导入org.jfree.data.time.TimeSeriesCollection;
导入org.jfree.data.xy.XYDataset;
导入java.awt.event.ActionListener;
导入java.awt.event.ActionEvent;

公共类Window扩展JFrame {
私人JPanel contentPane;

公共静态void main(String [] args){
EventQueue.invokeLater(new Runnable(){
公共无效run(){
尝试{
窗框= new Window();
frame.setVisible(true);
} catch(Exception e){
e.printStackTrace();
}
}
});
}

公共窗口(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,700,500);
contentPane =新的JPanel();
contentPane.setBorder(newEmptyBorder(5,5,5,5));
contentPane.setLayout(new BorderLayout(0,0));
setContentPane(contentPane);

JButton clickme = new JButton(“Click me”);
clickme.addActionListener(new ActionListener(){
公共无效actionPerformed(ActionEvent arg0){
contentPane.removeAll();
MyJPanel mypanel = new MyJPanel();
contentPane.add(mypanel,BorderLayout.CENTER);
validate();
mypanel.methodCalledOnceDisplayed();
}
});
contentPane.add(clickme,BorderLayout.NORTH);
JPanel示例= new JPanel();
example.add(new JLabel(“Example JPanel”));
contentPane.add(例如BorderLayout.CENTER);
}

}

类MyJPanel扩展JPanel实现ChartMouseListener {
私人ChartPanel chartPanel;
私人JFreeChart图表;
私有XYPlot subplotTop;
私有XYPlot subplotBottom;
私人的CombinedDomainXYPlot图;

公共MyJPanel(){
this.add(new JLabel(“此JPanel包含图表”));
createCombinedChart();
chartPanel =新的ChartPanel(图表);
chartPanel.addChartMouseListener(this);
this.add(chartPanel);
}

私人无效createCombinedChart(){
图=新的CombinedDomainXYPlot();
plot.setGap(30);
createSubplots();
plot.add(subplotTop,4);
plot.add(subplotBottom,1);
plot.setOrientation(PlotOrientation.VERTICAL);

chart = new JFreeChart(“Title”,new Font(“Arial”,Font.BOLD,20),plot,true);
}

私人无效createSubplots(){
subplotTop =新的XYPlot();
subplotBottom =新的XYPlot();

subplotTop.setDataset(emptyDataset(“Empty 1”));
subplotBottom.setDataset(emptyDataset(“Empty 2”));;
}

私人XYDataset emptyDataset(字符串标题){
TimeSeries ts = new TimeSeries(title);
TimeSeriesCollection tsc =新的TimeSeriesCollection();
tsc.addSeries(ts);
返回tsc;
}

@Override
public void chartMouseMoved(ChartMouseEvent e){
System.out.println(“鼠标移动!”);
}
@Override
公共无效chartMouseClicked(ChartMouseEvent arg0){}

公共无效methodCalledOnceDisplayed(){
JOptionPane.showMessageDialog(null,“Magic!”); //尝试注释此行并查看控制台
chartPanel.repaint();
//现在我们可以获取图表区域
this.chartPanel.getChartRenderingInfo()。getPlotInfo()。getSubplotInfo(0).getDataArea();
this.chartPanel.getChartRenderingInfo()。getPlotInfo()。getSubplotInfo(1).getDataArea();
}
}

查看使用和不使用JOptionPane时发生的情况。

最佳答案

为什么会发生这种情况的解释会很好。

您可以从以下变体中获得一些见解。注意

  • Swing GUI对象应该仅在event dispatch thread(EDT)上构造和操作,原因是建议使用here
  • 即使用户交互仅限于模式对话框,EDT仍将继续处理事件,如示例中所示。
  • 使用repaint()时不需要调用ChartPanel
  • 比手动容器操作更喜欢 CardLayout JTabbedPane
  • 而不是调用setPreferredSize(),而是覆盖getPreferredSize(),如here所述。

  • 附录:您删除了显示问题的两行……。
    ChartRenderingInfo是动态数据,在呈现图表之前不存在。模式图对话框在后台更新图表时处理事件。没有它,您可以通过将方法包装在适合RunnableinvokeLater()中来安排方法:
    EventQueue.invokeLater(new Runnable() {
    
        @Override
        public void run() {
            myPanel.methodCalledOnceDisplayed();
        }
    });
    

    更好的方案是在您知道数据有效的侦听器中访问ChartRenderingInfo,即由ChartPanel实现的侦听器。
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.border.EmptyBorder;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.axis.DateAxis;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.plot.CombinedDomainXYPlot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.plot.PlotRenderingInfo;
    import org.jfree.chart.plot.XYPlot;
    import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
    import org.jfree.data.time.Day;
    import org.jfree.data.time.TimeSeries;
    import org.jfree.data.time.TimeSeriesCollection;
    import org.jfree.data.xy.XYDataset;
    
    /**
    * @see https://stackoverflow.com/a/14894894/230513
    */
    public class Test extends JFrame {
    
        private JPanel panel;
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    Test frame = new Test();
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public Test() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final MyJPanel myPanel = new MyJPanel();
            panel = new JPanel() {
    
                @Override
                public Dimension getPreferredSize() {
                    return myPanel.getPreferredSize();
                }
            };
            panel.setBorder(new EmptyBorder(5, 5, 5, 5));
            panel.setLayout(new BorderLayout());
            add(panel);
    
            myPanel.start();
            JButton clickme = new JButton("Click me");
            clickme.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    panel.removeAll();
                    panel.add(myPanel, BorderLayout.CENTER);
                    validate();
                    EventQueue.invokeLater(new Runnable() {
    
                        @Override
                        public void run() {
                            myPanel.methodCalledOnceDisplayed();
                        }
                    });
                }
            });
            panel.add(clickme, BorderLayout.NORTH);
            JPanel example = new JPanel();
            example.add(new JLabel("Example JPanel"));
            panel.add(example, BorderLayout.CENTER);
        }
    
        private static class MyJPanel extends JPanel {
    
            private static final Random r = new Random();
            private ChartPanel chartPanel;
            private JFreeChart chart;
            private XYPlot subplotTop;
            private XYPlot subplotBottom;
            private CombinedDomainXYPlot plot;
            private Timer timer;
            private Day now = new Day(new Date());
    
            public MyJPanel() {
                this.add(new JLabel("Chart panel"));
                createCombinedChart();
                chartPanel = new ChartPanel(chart);
                this.add(chartPanel);
                timer = new Timer(1000, new ActionListener() {
    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        update(subplotTop);
                        update(subplotBottom);
                    }
                });
                timer.start();
            }
    
            public void start() {
                timer.start();
            }
    
            private void update(XYPlot plot) {
                TimeSeriesCollection t = (TimeSeriesCollection) plot.getDataset();
                for (int i = 0; i < t.getSeriesCount(); i++) {
                    TimeSeries s = t.getSeries(i);
                    s.add(now, Math.abs(r.nextGaussian()));
                    now = (Day) now.next();
                }
            }
    
            private void createCombinedChart() {
                plot = new CombinedDomainXYPlot();
                plot.setGap(30);
                createSubplots();
                plot.add(subplotTop, 4);
                plot.add(subplotBottom, 1);
                plot.setOrientation(PlotOrientation.VERTICAL);
                chart = new JFreeChart("Title",
                    JFreeChart.DEFAULT_TITLE_FONT, plot, true);
                plot.setDomainAxis(new DateAxis("Domain"));
            }
    
            private void createSubplots() {
                subplotTop = new XYPlot();
                subplotBottom = new XYPlot();
                subplotTop.setDataset(emptyDataset("Set 1"));
                subplotTop.setRenderer(new XYLineAndShapeRenderer());
                subplotTop.setRangeAxis(new NumberAxis("Range"));
                subplotBottom.setDataset(emptyDataset("Set 2"));
                subplotBottom.setRenderer(new XYLineAndShapeRenderer());
                subplotBottom.setRangeAxis(new NumberAxis("Range"));
            }
    
            private XYDataset emptyDataset(String title) {
                TimeSeriesCollection tsc = new TimeSeriesCollection();
                TimeSeries ts = new TimeSeries(title);
                tsc.addSeries(ts);
                return tsc;
            }
    
            public void methodCalledOnceDisplayed() {
                PlotRenderingInfo plotInfo =
                    this.chartPanel.getChartRenderingInfo().getPlotInfo();
                for (int i = 0; i < plotInfo.getSubplotCount(); i++) {
                    System.out.println(plotInfo.getSubplotInfo(i).getDataArea());
                }
                JOptionPane.showMessageDialog(null, "Magic!");
            }
        }
    }
    

    附录:进行一次额外的迭代来说明ChartMouseListener并清除一些松散的结局。
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import org.jfree.chart.ChartMouseEvent;
    import org.jfree.chart.ChartMouseListener;
    import org.jfree.chart.ChartPanel;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.axis.DateAxis;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.entity.ChartEntity;
    import org.jfree.chart.plot.CombinedDomainXYPlot;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.plot.XYPlot;
    import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
    import org.jfree.data.time.Day;
    import org.jfree.data.time.TimeSeries;
    import org.jfree.data.time.TimeSeriesCollection;
    import org.jfree.data.xy.XYDataset;
    
    /**
     * @see https://stackoverflow.com/a/14894894/230513
     */
    public class Test {
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    Test t = new Test();
                }
            });
        }
    
        public Test() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final MyJPanel myPanel = new MyJPanel();
            f.add(myPanel, BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            myPanel.start();
        }
    
        private static class MyJPanel extends JPanel {
    
            private static final Random r = new Random();
            private ChartPanel chartPanel;
            private JFreeChart chart;
            private XYPlot subplotTop;
            private XYPlot subplotBottom;
            private CombinedDomainXYPlot plot;
            private Timer timer;
            private Day now = new Day(new Date());
    
            public MyJPanel() {
                createCombinedChart();
                chartPanel = new ChartPanel(chart);
                this.add(chartPanel);
                timer = new Timer(1000, new ActionListener() {
    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        update(subplotTop);
                        update(subplotBottom);
                        now = (Day) now.next();
                    }
                });
                chartPanel.addChartMouseListener(new ChartMouseListener() {
    
                    @Override
                    public void chartMouseClicked(ChartMouseEvent e) {
                        final ChartEntity entity = e.getEntity();
                        System.out.println(entity + " " + entity.getArea());
                    }
    
                    @Override
                    public void chartMouseMoved(ChartMouseEvent e) {
                    }
                });
            }
    
            public void start() {
                timer.start();
            }
    
            private void update(XYPlot plot) {
                TimeSeriesCollection t = (TimeSeriesCollection) plot.getDataset();
                for (int i = 0; i < t.getSeriesCount(); i++) {
                    TimeSeries s = t.getSeries(i);
                    s.add(now, Math.abs(r.nextGaussian()));
                }
            }
    
            private void createCombinedChart() {
                plot = new CombinedDomainXYPlot();
                createSubplots();
                plot.add(subplotTop, 4);
                plot.add(subplotBottom, 1);
                plot.setOrientation(PlotOrientation.VERTICAL);
                chart = new JFreeChart("Title",
                    JFreeChart.DEFAULT_TITLE_FONT, plot, true);
                plot.setDomainAxis(new DateAxis("Domain"));
            }
    
            private void createSubplots() {
                subplotTop = new XYPlot();
                subplotBottom = new XYPlot();
                subplotTop.setDataset(emptyDataset("Set 1"));
                subplotTop.setRenderer(new XYLineAndShapeRenderer());
                subplotTop.setRangeAxis(new NumberAxis("Range"));
                subplotBottom.setDataset(emptyDataset("Set 2"));
                subplotBottom.setRenderer(new XYLineAndShapeRenderer());
                subplotBottom.setRangeAxis(new NumberAxis("Range"));
            }
    
            private XYDataset emptyDataset(String title) {
                TimeSeriesCollection tsc = new TimeSeriesCollection();
                TimeSeries ts = new TimeSeries(title);
                tsc.addSeries(ts);
                return tsc;
            }
        }
    }
    

    10-08 01:58