问题
I'm trying to use the jmathplot library in a swing application.
Problem is, it doesn't seem to work when I add it to a JPanel as follows:
// create your PlotPanel (you can use it as a JPanel)
double[] x = new double[] { 0, 1, 2, 3, 4, 5 };
double[] y = new double[] { 10, 11, 12, 14, 15, 16 };
// create your PlotPanel (you can use it as a JPanel)
Plot2DPanel graph = new Plot2DPanel();
graph.setBounds(0, 0, 782, 272);
// add a line plot to the PlotPanel
graph.addLinePlot("my plot", x, y);
JPanel panel = new JPanel();
panel.setBounds(10, 333, 782, 272);
tab_analysis.add(panel);
panel.setLayout(null);
panel.add(graph);
Because the plot doesn't show up and I get weird axes as well:
The site states:
use the PlotPanel as any Swing component (all PlotPanel extends JPanel, in fact)
What do I do wrong?
回答1:
works with
NullLayout
, without any issue, but I'm quite not familair with this layout manager (delegateInsets
from parent), then I'm leaving any comments aboutsimple don't to use
NullLayout
override
getPreferredSize
forPlot2DPanel
JPanel
hasFLowLayout
(with the same output as fromNullLayout
! on resize), accepting onlyPreferredSize
, child aren't resizable with its contianer, is required to useBorderLayout
/GridLayout
for simple graph
.
..
from code
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.math.plot.Plot2DPanel;
public class MyPlot {
private JFrame frame = new JFrame("JMathPlot library in a swing application.");
private JPanel panel = new JPanel();
public MyPlot() {
double[] x = new double[]{0, 1, 2, 3, 4, 5};
double[] y = new double[]{10, 11, 12, 14, 15, 16};
Plot2DPanel plot = new Plot2DPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
};
plot.addLinePlot("my plot", x, y); // add a line plot to the PlotPanel
panel.setLayout(new BorderLayout());
panel.add(plot);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MyPlot();
}
});
}
}
回答2:
You can see here examples if you want Jean-Paul:
http://jmathtools.berlios.de/doku.php?id=jmathplot:tutorial
来源:https://stackoverflow.com/questions/18315407/jmathplot-doesnt-work-in-swing-application