Drawing a line on a JFrame(在 JFrame 上画一条线)
本文介绍了在 JFrame 上画一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Graphics 2D 绘制一条线,但随后这条线出现在所有JFrame 中的其他组件,从而使它们不可见.我该如何解决这个问题?
I am trying to draw a line using the Graphics 2D but then the line appears over all the
other components in the JFrame thus making them invisible. How do I correct this problem?
代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
class Success extends JFrame{
public Success(){
JPanel panel=new JPanel();
getContentPane().add(panel);
setSize(450,450);
JButton button =new JButton("press");
panel.add(button);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}
public static void main(String []args){
Success s=new Success();
s.setVisible(true);
}
}
推荐答案
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
class Success extends JFrame{
public Success(){
JPanel panel=new JPanel();
getContentPane().add(panel);
setSize(450,450);
JButton button =new JButton("press");
panel.add(button);
}
public void paint(Graphics g) {
super.paint(g); // fixes the immediate problem.
Graphics2D g2 = (Graphics2D) g;
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}
public static void main(String []args){
Success s=new Success();
s.setVisible(true);
}
}
更多提示
- 在 EDT 上创建 GUI.有关详细信息,请参阅 Swing 中的并发.
- 按照@nIcEcOw 的建议使用
JPanel,覆盖paintComponent(Graphics)而不是paint().再次,首先调用super方法. - 不要扩展框架,只使用一个实例.使用
pack()根据组件所需空间设置大小.
- Create the GUI on the EDT. See Concurrency in Swing for more details.
- Use a
JPanelas suggested by @nIcEcOw, overridepaintComponent(Graphics)instead ofpaint(). Again, call thesupermethod first. - Don't extend frame, just use an instance of one. Set the size according to the space required for the components using
pack().
这篇关于在 JFrame 上画一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:在 JFrame 上画一条线
基础教程推荐
猜你喜欢
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
