小程序内容在调整大小时消失
我从来没有做过Applet开发。尝试一些非常简单的事情。基本上我是在窗户上画一条绳子。但是,每当我调整窗口大小时,内容就会消失。
SO 上的类似建议问题建议重写 update() 方法来调用 repaint()。我尝试过,但仍然没有成功。另外,如何将字符串(“Hello World!”)在窗口上居中(以便即使在调整大小时它也保持居中)?
这是代码:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class TestApplet extends JApplet
{
public void init(){
setBackground (Color.gray);
}
public void paint (Graphics page){
String name = "Hello World!";
page.drawString(name,100,100);
}
public void update(Graphics page){
this.repaint();
}
}
I have never done Applet development. Trying something very simple. Basically I am drawing a string on the window. However, whenever I re-size the window the content disappears.
A similar suggested question on SO recommended overriding the update() method to call repaint(). I tried that but that still didn't do it. Also how can I center the string ("Hello World!") on the window (so that it stays centered even on resize)?
Here is the code:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class TestApplet extends JApplet
{
public void init(){
setBackground (Color.gray);
}
public void paint (Graphics page){
String name = "Hello World!";
page.drawString(name,100,100);
}
public void update(Graphics page){
this.repaint();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是用于 AWT 应用程序的旧代码。您永远不应该重写 JApplet 的 Paint() 或 update() 方法。
使用 Swing 时,自定义绘制是通过重写 JPanel(或 JComponent)的 PaintComponent() 方法来完成的。然后将该面板添加到小程序的内容窗格中。
阅读 Swing 教程中有关 自定义绘画 的部分,了解示例和更多细节。本教程还有一个关于“如何制作小程序”的部分,您应该看看。
使用 getSize() 方法获取父面板的大小。然后除以 2。尽管您需要记住 Y 坐标是文本的底部而不是顶部。因此,您还需要考虑字体的 FontMetrics 以了解文本的确切高度。您可以从 Graphics 对象获取 FontMetrics。
This is old code used for AWT applications. You should never override the paint() or update() methods of a JApplet.
When using Swing custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent). Then you add the panel to the content pane of the applet.
Read the section from the Swing tutorial on Custom Painting for examples and more details. The tutorial also has a section on "How to Make Applets" that you should look at.
Get the size of the parent panel by using the getSize() method. Then divide by 2. Although you need to remember that the Y coordinated is the bottom of the text not the top. So you would also need to consider the FontMetrics of the Font to know the exact height of the text. You can get the FontMetrics from the Graphics object.