帮助在 Swing 中绘制自定义图形
我知道我没有在主机中调用图形绘制命令来显示它。但我不知道怎么做。 提前致谢
import java.awt.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static Panel panel = new Panel();
public MainFrame() {
panel.setBackground(Color.white);
Container c = getContentPane();
c.add(panel);
}
public void paint(Graphics g) {
g.drawString("abc", 20, 20);
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I know that i am not calling the graphics paint command in the mainframe in order to display it. but i'm not sure how.
thanks in advance
import java.awt.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static Panel panel = new Panel();
public MainFrame() {
panel.setBackground(Color.white);
Container c = getContentPane();
c.add(panel);
}
public void paint(Graphics g) {
g.drawString("abc", 20, 20);
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
阅读 Swing 教程中有关 自定义绘制 的部分以获取工作示例绘画以及其他 Swing 基础知识。
另外,不要使用Panel,它是一个AWT 类。使用 JPanel,它是一个 Swing 类。
Read the section from the Swing tutorial on Custom Painting for working examples on painting as well as other Swing basics.
Also, don't use Panel, that is an AWT class. Use JPanel which is a Swing class.
创建一个扩展 JComponent 的新类,覆盖 public void PaintComponent(Graphics g) 方法并绘制字符串。
将这个覆盖的组件添加到您的框架中。例如:frame.getContentPane().add(customComponent);
Create a new class that extends JComponent override the public void paintComponent(Graphics g) method and draw your string.
Add this overridded component to your frame. Like:
frame.getContentPane().add(customComponent);
首先,您需要在 中创建 AWT / Swing 内容事件调度线程。其次,您不应该覆盖主窗口上的绘制。您需要创建
Component
的子类并重写paintComponent(Graphics g)
方法,将您目前在paint
中拥有的任何内容放入其中。之后,将组件添加到框架中。根据您的需要,您可能需要使用布局管理器。First of all, you need to create your AWT / Swing stuff in the Event Dispatch Thread. Second of all, you shouldn't be overriding paint on the main window. You need to create a subclass of
Component
and override thepaintComponent(Graphics g)
method, putting in there whatever you have inpaint
at the moment. After this, add the component to the frame. You might need to mess with layout managers depending on your needs.您可以创建一个扩展 JPanel 的类,如下所示:
然后您可以将该面板添加到您的 JFrame 中。
You can create a class that extends JPanel like this:
Then you can add that panel to your JFrame.