我有一个jframe,上面有一个jpanel,面板通常必须使用repaint()和revalidate()来更改其内容。我设法将图像,文本和按钮按我希望它们放在此jpanel上的方式放置。一切正常,但是现在我尝试为jframe设置背景,这不会干扰其上方的内容。例如,如果有一棵树的绘图,它应该出现在jpanel文本的后面,而不会破坏它。我发现半有效的方法是在jframe上使用setContentPane(),添加一个类,该类扩展了jpanel并覆盖了paintComponent()。一切都出现在屏幕上,但是文本被垂直压缩,并且元素向框架顶部移动。
如果我不使用setContentPane()而是将背景类添加到框架中,则不管jpanel的setOpaque()都不会显示。 我还尝试使用jLayeredPane,因为我在互联网上阅读的内容表明这是正确的答案。但是,我无法使其正常工作,并且背景仍然隐藏。
private final int WIDTH = 1024;
private final int HEIGHT = 768;
Frame()
{
JFrame frame = new JFrame();
panel = new JPanel();
gbc = new GridBagConstraints();
//Unrelated elements
//font = new Font(Font.MONOSPACED, Font.PLAIN, 20);
//border = BorderFactory.createEmptyBorder();
//imageResizer = new ImageResizer();
frame.setTitle("Shady Path");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setIconImage(new ImageIcon("res/human.png").getImage());
frame.setContentPane(new DrawPanel());
panel.setLayout(new GridBagLayout());
panel.setOpaque(false);
gbc.anchor = GridBagConstraints.PAGE_START;
frame.add(panel);
frame.setVisible(true);
}
//One of the two methods that change the contents of the jpanel
void appendMain(String mainImage, JTextArea mainText, JButton button)
{
panel.removeAll();
image = new JLabel(imageResizer.resize(200, 200, mainImage));
gbc.insets = new Insets(0, 0, 30, 0);
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(image, gbc);
formatText(mainText);
panel.add(mainText, gbc);
button.setFont(font);
button.setForeground(Color.WHITE);
button.setBackground(Color.BLACK);
button.setBorder(border);
gbc.fill = GridBagConstraints.VERTICAL;
gbc.insets = new Insets(50, 0, 70, 0);
panel.add(button, gbc);
panel.revalidate();
panel.repaint();
}
//This is for the text formating
private void formatText(JTextArea baseText)
{
baseText.setEditable(false);
baseText.setForeground(Color.WHITE);
baseText.setFont(font);
baseText.setLineWrap(true);
baseText.setWrapStyleWord(true);
baseText.setMargin(new Insets(0, 300, 0, 300));
baseText.setOpaque(false);
gbc.insets = new Insets(30, 0, 0, 0);
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
}
//The following code is for the paintComponent() class
//The imageResizer is another class that I made, but it just resizes images and it is unrelated.
public class DrawPanel extends JPanel
{
private Image image;
public DrawPanel()
{
ImageResizer imageResizer = new ImageResizer();
ImageIcon imageIcon = imageResizer.resize(1024, 768, "res/test.png");
image = imageIcon.getImage();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
答案 0 :(得分:1)
好吧... @HovercraftFullOfEels似乎对他的评论是正确的。从字面上看,我只需要将DrawPanel的布局设置为BorderLayout即可,而所有内容都是固定的。
public DrawPanel()
{
this.setLayout(new BorderLayout());
ImageResizer imageResizer = new ImageResizer();
ImageIcon imageIcon = imageResizer.resize(1024, 768, "res/test.png");
image = imageIcon.getImage();
}