我正在使用paintComponent为类赋值创建一个GUI,它根本不会影响GUI的外观。首先,我只是将背景设置为白色。以下代码有效:
import javax.swing.*;
import java.awt.*;
public class PA05a extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("MouseDrawDemo");
JPanel content = new JPanel();
content.setBackground(Color.WHITE);
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(120,70);
window.setSize(400,300);
window.setVisible(true);
}
}
但这不是:
import javax.swing.*;
import java.awt.*;
public class PA05a extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("MouseDrawDemo");
JPanel content = new JPanel();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(120,70);
window.setSize(400,300);
window.setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
//add backdrop
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
}
}
我不能只是不使用paintComponent,因为我稍后会添加将逐帧更改的内容。有人可以找出我遗失的地方吗?
答案 0 :(得分:1)
JPanel content = new PA05a();
您没有创建PA05a的对象。 ;)
答案 1 :(得分:0)
你忘了创建你的对象。将您的代码更改为:
import javax.swing.*;
import java.awt.*;
public class PA05a extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("MouseDrawDemo");
JPanel content = new PA05a();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(120,70);
window.setSize(400,300);
window.setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
//add backdrop
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
}
}