我正在尝试在JFrame
中绘制一条线,但未绘制出一条线。
我尝试对setOpaque(true)
,contentPane
和lblNewLabel
使用方法l
,但没有任何变化。我也尝试在此类课外致电repaint();
,但情况仍然相同。这是代码:
public class DrawingClass extends JFrame
{
private JPanel contentPane;
public DrawingClass(int n, int s, int p) {
Line l= new Line();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(700, 300, 480, 640);
contentPane = new JPanel();
contentPane.setOpaque(true);
setResizable(false);
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("image.png"));
lblNewLabel.setBounds(0, 0, 480, 640);
contentPane.add(lblNewLabel);
l.setBounds(0,0,480,640);
contentPane.add(l);
repaint();
}
class Line extends JPanel
{
public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(10, 10, 15, 12);
}
}
}
我希望在JFrame左上角的背景墙纸上方有一条线,但是什么也没发生。它仅显示墙纸。
答案 0 :(得分:1)
您的代码中有几个错误:
您正在扩展JFrame
,但没有更改其行为,那么为什么要这样做呢? JFrame
是一个刚性组件,因此扩展它,而不是基于JPanel
来构建GUI从来不是一个好主意。参见:Extends JFrame vs. creating it inside the program
未明确设置JFrame
的大小,在其上调用pack()
,而是从getPreferredSize
覆盖JPanel
,请参见:{{3 }}
在这种情况下,您无需致电setOpaque(...)
。
不要使用null-layout
,它可能会导致Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?,因为strange errors和null Layout is Evil
我们无权访问您的图片,因此我们无法测试ImageIcon
,它也与您的问题无关。但是,您应该frowned upon
不要显式设置每个元素的边界,这与点(4)有关,您应该使用load your images as resources或它们的组合来获得所需的边界GUI。
不要那样调用repaint()
,它没有任何作用,应该在UI发生变化时重新绘制UI。但是,程序开始时没有任何变化。
您正在通过不调用super.paintComponent(...)
方法内的paintComponent(...)
来破坏绘画链。检查Layout Manager,以便学习正确的方法
请注意,paintComponents(...)
(后跟s
)与paintComponent(...)
(请看标题)不同
因此,在完成上述所有更改之后,我们进入了以下简单程序:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DrawingClass {
private JPanel contentPane;
private JFrame frame;
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> new DrawingClass().createAndShowGUI());
}
public void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
Line line = new Line();
frame.add(line);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
class Line extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(10, 10, 15, 12);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(480, 640);
}
}
}
哪个会产生以下输出: