在相同 class 的框架中添加 class extends jpanel 的对象
add a object of a class extends jpanel in a frame in same class
我正在尝试制作一个 class,当我们在 main 方法中制作这个 class 的对象时,显示 window 青色
在我最后的程序中我写了一个 class extends jpanel (example:Test extends JPanel
) 然后在 main class 我只是在框架中添加了一个测试对象
但现在我想在测试中做到这一点
通常只是制作一个测试对象 class 我想看到一个青色 window 这是我不完整的代码 :
public class BoardFrame extends JPanel {
private int rowNumber,columnNumber;
private JFrame mainFrame;
public BoardFrame(int m,int n){
rowNumber = m;
columnNumber = n;
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.cyan);
}
}
你所要做的就是 mainFrame.add(this);
然后 mainFrame.setVisible(true);
如果你想使用g.setColor(Color.cyan);
,你必须画一些东西。
使用g.fillRect(0, 0, this.getWidth(), this.getHeight());
或者您可以在构造函数中使用 this.setBackground(Color.cyan);
。
这是您完整的固定代码。试试吧!
public class BoardFrame extends JPanel {
public static void main(String[] args) {
new BoardFrame();
}
private int rowNumber, columnNumber;
private JFrame mainFrame;
public BoardFrame(int m, int n) {
rowNumber = m;
columnNumber = n;
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setBackground(Color.cyan); // replaces need for paintComponent
mainFrame.add(this); // <-- added this line
mainFrame.setVisible(true);
}
public void paintComponent(Graphics g) {
g.setColor(Color.cyan);
g.fillRect(0, 0, this.getWidth(), this.getHeight()); // <-- added this line
}
}
我正在尝试制作一个 class,当我们在 main 方法中制作这个 class 的对象时,显示 window 青色
在我最后的程序中我写了一个 class extends jpanel (example:Test extends JPanel
) 然后在 main class 我只是在框架中添加了一个测试对象
但现在我想在测试中做到这一点
通常只是制作一个测试对象 class 我想看到一个青色 window 这是我不完整的代码 :
public class BoardFrame extends JPanel {
private int rowNumber,columnNumber;
private JFrame mainFrame;
public BoardFrame(int m,int n){
rowNumber = m;
columnNumber = n;
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.cyan);
}
}
你所要做的就是 mainFrame.add(this);
然后 mainFrame.setVisible(true);
如果你想使用g.setColor(Color.cyan);
,你必须画一些东西。
使用g.fillRect(0, 0, this.getWidth(), this.getHeight());
或者您可以在构造函数中使用 this.setBackground(Color.cyan);
。
这是您完整的固定代码。试试吧!
public class BoardFrame extends JPanel {
public static void main(String[] args) {
new BoardFrame();
}
private int rowNumber, columnNumber;
private JFrame mainFrame;
public BoardFrame(int m, int n) {
rowNumber = m;
columnNumber = n;
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setBackground(Color.cyan); // replaces need for paintComponent
mainFrame.add(this); // <-- added this line
mainFrame.setVisible(true);
}
public void paintComponent(Graphics g) {
g.setColor(Color.cyan);
g.fillRect(0, 0, this.getWidth(), this.getHeight()); // <-- added this line
}
}