我不知道我做错了什么,因为我以前在各种开源程序和游戏中见过这种情况无数次。下面是我的代码,它给了我g2不是赋值变量的错误?我很困惑..。
package scratch;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class okay {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("helllo", JLabel.CENTER);
emptyLabel.setPreferredSize(new Dimension(250, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public void paint ( Graphics g ){
Graphics2D g2 = (Graphics2D) g;
g2.drawString("hello",0,0);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
paint(g2);
}
});
}
}发布于 2014-08-13 19:35:56
您的类没有扩展任何Swing组件,因此paint方法不是覆盖,什么也不做。相反,您应该让类扩展JPanel,将这个JPanel放入JFrame中,并重写paintComponent。此外,始终给出您认为是重写超级方法的方法-- @Override注释。这样,编译器就会立即告诉您,您所做的是错误的。2)不要在学习新的Java特性时猜测--在尝试使用这些特性之前,先看看并学习适当的教程。在这里,绘画在秋千教程将回答这些问题为您。
例如,
public class Foo extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("hello", 0, 20);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new Foo());
frame.pack();
frame.setVisible(true);
}
}https://stackoverflow.com/questions/25294362
复制相似问题