这就是我正在做的但是没有什么东西在Jframe窗口上显示。我没有扩展类JFrame来做我的,是否有必要在窗口上显示对象。
public class testGraphics {
static JFrame workingFrame = null;
public static void main(String args[])
{
JFrame workingManager = new JFrame("Hello");
workingManager.setSize(500, 500);
workingManager.setVisible(true);
Graphics g = workingManager.getGraphics();
JPanel jp = (JPanel) workingManager.getContentPane();
workingManager.paintComponents(g);
g.fillOval(0, 0, 30, 30);
g.drawOval(0, 50, 30, 30);
g.setColor(Color.CYAN);
}
}
答案 0 :(得分:1)
不曾呼叫getGraphics()
或明确调用paintXxx()
进行自定义绘画。自定义绘制的正确方法是覆盖要绘制的面板的paintComponent
方法。 overriden方法将隐式调用 for 。然后将该面板添加到框架中。你也应该覆盖面板的getPreferredSize()
,因此它有一个首选尺寸,所以你可以打包框架
class PaintPanel extends JPanel {
@Override
protected paintComponent(Grapchics g) {
super.paintComponent(g);
g.drawString(....);
}
@Override
public Dimension getPreferredSize() {'
return new Dimension(300, 300);
}
}
然后将其添加到框架中(或者如果要将其设置为框架的内容窗格,请执行此操作)
PaintPanel panel = new PaintPaint();
frame.add(panel);
...
frame.pack();
了解详情
答案 1 :(得分:1)
我对您的代码进行了一些更改,以使其正常工作。
我更改了main方法以调用SwingUtilities invokeLater方法,以确保在Event Dispatch thread上定义并使用了Swing组件。
我创建了一个绘图JPanel。我先设置颜色,然后绘制椭圆。
我添加了JFrame默认关闭操作。您必须指定默认关闭操作,否则关闭JFrame后Java应用程序将继续运行。
我将尺寸移到了绘图面板。调用JFrame包方法时,将计算帧大小。
这是修改后的代码:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGraphics implements Runnable{
private JFrame workingManager;
private JPanel drawingPanel;
@Override
public void run() {
workingManager = new JFrame("Hello");
workingManager.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingPanel = new DrawingPanel();
workingManager.add(drawingPanel, BorderLayout.CENTER);
workingManager.pack();
workingManager.setLocationByPlatform(true);
workingManager.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new TestGraphics());
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID =
-3701718376300985046L;
public DrawingPanel() {
this.setPreferredSize(new Dimension(500, 500));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.CYAN);
g.fillOval(0, 0, 30, 30);
g.drawOval(0, 50, 30, 30);
}
}
}
答案 2 :(得分:0)
setSize()
和setVisible()
必须位于方法的底部:
JFrame workingManager = new JFrame("Hello");
Graphics g = workingManager.getGraphics();
JPanel jp = (JPanel) workingManager.getContentPane();
workingManager.paintComponents(g);
g.fillOval(0, 0, 30, 30);
g.drawOval(0, 50, 30, 30);
g.setColor(Color.CYAN);
workingManager.setSize(500, 500);
workingManager.setVisible(true);