[英]The paint function is not called in Java Swing
我的目的 - 使用 Java Swing 创建一个带线的板。
在我制作了一块木板并为其上色之后,我尝试制作线条。 为此,我继承自 JPanel 并添加了 paintComponent 方法。 但是当我运行应用程序时,没有调用该方法。
我用 super(); 添加了默认构造函数; 我还添加到被调用的构造函数 super();
我仍然无法运行 paint 方法或 paintComponent 方法;
我尝试了以下所有帖子: Java Swing paint() not working Insert Button in JPanel
public class Main {
public static void main(String[] args) {
Board board = new Board(295, 295, "Go board");
}
}
import java.awt.*;
import javax.swing.*;
public class Board extends JPanel{
private int width;
private int height;
private String title;
private JFrame JFrame;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public JFrame getJFrame() {
return JFrame;
}
public void setJFrame(JFrame JFrame) {
this.JFrame = JFrame;
}
public Board(int width, int height, String title){
super();
this.width = width;
this.height = height;
this.title = title;
this.initBoard();
}
public Board(){
super();
}
public void initBoard(){
JFrame f = new JFrame(this.getTitle());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.getHSBColor(25, 75, 47));
f.setSize(this.getWidth(), this.getHeight());
f.setLocation(550, 25);
f.setVisible(true);
this.setJFrame(f);
}
public void paint(Graphics g) {
g.drawLine(10, 10, 250, 10);
System.out.println("Test paint");
}
public void paintComponent(Graphics g) {
g.drawLine(10, 10, 250, 10);
System.out.println("Test paintComponent");
}
}
您从未调用过包含initBoard
(这是糟糕的设计)的JFrame
。 您还必须使用jframe.add(this);
最好单独使用框架,然后像这样将组件添加到其中
public static void main(){
JFrame f=new JFrame();
///set all the dimensions and other stuff of the frame
f.setLayout(new BorderLayout);
f.add(new Board(295, 295, "Go board"),BorderLayour.CENTER);
f.setVisible();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.