【发布时间】:2021-10-21 09:50:27
【问题描述】:
我的目的 - 使用 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");
}
}
【问题讨论】:
-
首先,不要将你的JFrame命名为JFrame,使用“frame”来避免混淆。其次,需要在paintComponent方法中调用super方法; paintComponent 方法的第一行应该是 super.paintComponent(g);删除您的其他绘画方法,以免出现其他错误。第三,您的 Board 类中有 2 个不同的帧:JFrame 和 f,组合成一个 JFrame。最后,使用 f.add(this) 代替 this.setFrame(f);并在添加面板后调用 f.setVisible(true) 以避免任何错误。
标签: java swing user-interface jpanel paintcomponent