我正在尝试在JPanel中显示一条消息。我使用了Graphics类的drawString()函数。下面是我的代码:
public class Frame {
JFrame frame;
JPanel panel;
Graphics graph;
Frame() {
frame = new JFrame();
panel = new JPanel();
frame.setTitle("My wonderful window");
frame.setSize(800, 600);
frame.ContentPane(panel);
frame.setVisible(true);
}
void displayMessage(String message) {
graph = new Graphics();
graph.drawString(message, 10, 20);
}
}我有这个错误:error: Graphics is abstract; cannot be instantiated
发布于 2013-10-09 15:40:05
重写JPanel的paintComponent(Graphics g)方法。在该方法中,您可以访问有效的Graphics实例。该方法在每个绘制上调用。
但是在面板中添加一个JLabel可能会更好。标签最初没有文本,当您收到消息时,只需调用标签的setText(messageText)即可。
发布于 2021-07-08 00:12:22
您应该为JFrame和JPanel创建子类,并覆盖所需的方法。您可以尝试如下所示:
package test;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame extends JFrame {
public static final String message = "HELLO WORLD!!!";
public class Panel extends JPanel {
public void paintComponent(Graphics graph) {
graph.drawString(message, 10, 20);
}
}
public Frame() {
Panel panel = new Panel();
this.setTitle("My wonderful window");
this.setSize(800, 600);
this.setContentPane(panel);
this.setVisible(true);
}
public static void main(String[] args) {
new Frame();
}
}此外,还有很多关于这方面的好书/教程。你应该读一本。
编辑:你还应该阅读所有的JComponents (JButtons,JLabels...)。它们相当有用。
https://stackoverflow.com/questions/19265765
复制相似问题