【发布时间】:2020-12-27 16:18:43
【问题描述】:
这是我年终项目的一小部分,我正在尝试在 JFrame 中添加一条带有 JLabel 的直线。如果我删除 JLabel 则该行将显示,否则不会。我只知道java swing,因此我对java图形没有任何经验。
提前致谢 :)
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class Draw extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Draw frame = new Draw();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Draw() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 569, 461);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lbl = new JLabel("Show ");
lbl.setBounds(263, 90, 49, 14);
contentPane.add(lbl);
}
@Override
public void paint(Graphics g) {
g.drawLine(100, 100, 0, 0);
g.drawArc(200, 200, 120, 100, 0, 180);
}
}
【问题讨论】:
-
不要使用空布局。不要使用 setBounds()。不要覆盖 JFrame 上的paint()。自定义绘画是通过覆盖 JPanel 上的 paintComponent() 来完成的,然后将面板添加到框架中。框架的内容面板已经是一个JPanel,不需要再创建另一个面板。阅读 Custom Painting 上的 Swing 教程部分。下载其中一个工作示例并根据您的特定要求对其进行修改。
-
永远不要直接在 JFrame 中绘制,而是在 JPanel 中覆盖paintComponent,并且在覆盖任何绘制方法(paint、paintComponent、paintBorders...)时,您几乎总是需要在您的覆盖中调用相应的超级方法。