Java Swing 应用程序为什么不在屏幕上居中?



我已经下载了一个Java Swing应用程序,尽管我在应用程序中有这一行:demo.setLocationRelativeTo(null);

为什么它不在屏幕上居中?

程序看起来像这样:

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jfree.chart.*;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.DefaultXYZDataset;
import org.jfree.data.xy.XYZDataset;
public class Bubble_Chart_AWT extends JFrame
{
public Bubble_Chart_AWT(String s)
{
super(s);
JPanel jpanel=createDemoPanel();
jpanel.setPreferredSize(new Dimension(560,370));
setContentPane(jpanel);
}
private JFreeChart createChart(XYZDataset xyzdataset)
{
JFreeChart jfreechart=ChartFactory.createBubbleChart("AGE vs WEIGHT vs WORK",
"Weight",
"AGE",
xyzdataset,
PlotOrientation.HORIZONTAL,
true,true,false);
XYPlot xyplot=(XYPlot)jfreechart.getPlot();
xyplot.setForegroundAlpha(0.65F);
XYItemRenderer xyitemrenderer=xyplot.getRenderer();
xyitemrenderer.setSeriesPaint(0,Color.blue);
NumberAxis numberaxis=(NumberAxis)xyplot.getDomainAxis();
numberaxis.setLowerMargin(0.2);
numberaxis.setUpperMargin(0.5);
NumberAxis numberaxis1=(NumberAxis)xyplot.getRangeAxis();
numberaxis1.setLowerMargin(0.8);
numberaxis1.setUpperMargin(0.9);
return jfreechart;
}
public static XYZDataset createDataset()
{
DefaultXYZDataset defaultxyzdataset=new DefaultXYZDataset();
double ad[]={30,40,50,60,70,80};
double ad1[]={10,20,30,40,50,60};
double ad2[]={4,5,10,8,9,6};
double ad3[][]={ad,ad1,ad2};
defaultxyzdataset.addSeries("Series 1",ad3);
return defaultxyzdataset;
}
public JPanel createDemoPanel()
{
JFreeChart jfreechart=createChart(createDataset());
ChartPanel chartpanel=new ChartPanel(jfreechart);
chartpanel.setDomainZoomable(true);
chartpanel.setRangeZoomable(true);
return chartpanel;
}
public static void main(String args[])
{
SwingUtilities.invokeLater(() ->
{
Bubble_Chart_AWT demo=new Bubble_Chart_AWT("Bubble_Chart_AWT");
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.setLocationRelativeTo(null);
demo.pack();
demo.setVisible(true);
});
}
}

你需要这个 [ jfreechart-1.5.0.jar ] 在你的项目 "lib" 中从 http://repo1.maven.org/maven2/org/jfree/jfreechart/1.5.0/运行它。

我应该怎么做,它会自动在屏幕上居中,通常"demo.setLocationRelativeTo(null("有效,但在此应用程序中不起作用。

这可能会解决您的问题,它在我的系统上确实如此:

在呼叫setLocationRelativeTo(null)之前呼叫pack(),但在setVisible(true)之前呼叫setLocationRelativeTo(null),如下所示:

public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
Bubble_Chart_AWT demo = new Bubble_Chart_AWT("Bubble_Chart_AWT");
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.pack();
demo.setLocationRelativeTo(null);
demo.setVisible(true);
});
}

只需切换线条即可使图表在我的屏幕上居中。

相关内容

  • 没有找到相关文章

最新更新