问题描述
所以在课堂上我们正在制作一个Java程序。我们试图在JFrame中使用paint(Graphics g)函数。过去(几周前)我们尝试过它,并且它曾经工作过。但现在它没有(或者我们在某个地方犯了错误)。我们也尝试使用paintComponent(Graphics g),但似乎没有任何工作。这里是我们的代码:
public class MainAc {
public static void main(String [] args ){
JFrame frame = new JFrame(Class Paint);
JButton button = new JButton(Click for more);
frame.setSize(800,600);
frame.add(button);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setLayout(null);
button.setLocation(100,100);
button.setSize(200,100);
frame.setVisible(true);
public void paint(Graphics g){
g.drawString(Hello,200,50);
$ / code $ / pre
解决方案你在那里做的是在你自己的 MainAc 类中实现一个 paint c方法,而不是 JFrame 。
$ b 您的 MainAc 类本身应该从 JFrame 。
下面的代码应该可以工作。如果你不懂继承,你应该查看你的课堂笔记,它会在那里。
public class MainAc扩展JFrame {
public static void main(String [] args){
new MainAc();
public MainAc(){
super(Class Paint);
JButton button = new JButton(Click for more);
setSize(800,600);
add(button);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setLayout(null);
button.setLocation(100,100);
button.setSize(200,100);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
g.drawString(Hello,200,50);
}
}
So in class we are making a Java program. We are trying to use the paint(Graphics g) function in the JFrame. We have tried it in the past (weeks ago) and it used to work. But now it doesnt (or we made a mistake somewhere). We have also tried to use paintComponent(Graphics g) but nothing seems to work.Here is our code:
public class MainAc { public static void main(String[] args) { JFrame frame = new JFrame("Class Paint"); JButton button = new JButton("Click for more"); frame.setSize(800, 600); frame.add(button); frame.setLayout(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); button.setLayout(null); button.setLocation(100,100); button.setSize(200,100); frame.setVisible(true); } public void paint(Graphics g){ g.drawString("Hello", 200, 50); } }解决方案So what you're doing there, is implementing a paint method inside your own MainAc class, not the JFrame.
Your MainAc class itself, should derive from the JFrame.
The code below should work. If you don't understand inheritance, you should look over your class notes, it'll be in there.
public class MainAc extends JFrame { public static void main(String[] args) { new MainAc(); } public MainAc() { super("Class Paint"); JButton button = new JButton("Click for more"); setSize(800, 600); add(button); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); button.setLayout(null); button.setLocation(100,100); button.setSize(200,100); setVisible(true); } public void paint(Graphics g) { super.paint(g); g.drawString("Hello", 200, 50); } }
这篇关于在JFrame中绘制不工作(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!