[英]How do I get both my image and button to display?
目前,我要解决的问题是如何同时显示图像和按钮。
当我在代码中有以下行时,图像会显示,但当我删除它时,我的图像不会显示,但按钮会显示: setLayout (new FlowLayout());
图像例如^
import java.awt.*;
public class Panel extends JFrame {
private ImageIcon FirstPageImage;
private JLabel FirstPageLabel;
private JLayeredPane SignupButtonLayer;
private JButton Button;
public Panel(){
setLayout (new FlowLayout()) ;
FirstPageImage = new ImageIcon(getClass().getResource("FirstPageAnimationUsing.gif"));
FirstPageLabel = new JLabel(FirstPageImage);
FirstPageImage.setImage(FirstPageImage.getImage().getScaledInstance(343,820,Image.SCALE_DEFAULT));
add(FirstPageLabel);
Button = new JButton();
SignupButtonLayer = new JLayeredPane();
Button.setOpaque(true);
Button.setBackground(Color.cyan);
Button.setBounds(94,617,159,82);
SignupButtonLayer.add(Button, JLayeredPane.DEFAULT_LAYER);
add(SignupButtonLayer);
}
public static void main(String[] args) {
Panel gui = new Panel();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("Reminder App");
gui.setSize(360,850);
}
}
请参阅如何使用分层窗格。
JLayeredPane
提供首选大小。 由于您的JLayeredPane
仅包含一个JButton
,因此该大小应该足够大以显示整个JButton
。setBounds
的 arguments – 您在Button
上调用 – 是相对于它的容器,即SignupButtonLayer
。 将x设置为 94 并将y设置为 617 意味着Button
位于SignupButtonLayer
的边界之外。 因此你看不到它。 在下面的代码中,我将x和y都设置为 0(零),以便Button
的左上角与SignupButtonLayer
的左上角对齐。Button
显式调用方法setOpaque(true)
,因为无论如何这是默认设置。pack()
——这通常是首选——要么调用setSize()
,但不要同时调用两者。setVisible(true)
只应在您的 GUI 完全构建后调用。 在下面的代码中,我在调用pack()
和setTitle()
之后调用它。 下面的代码简单地解决了您的问题,即同时显示图像和按钮 - 同时将FlowLayout
用于 [content pane of the] JFrame
。 请注意, SignupButtonLayer
的首选大小略大于方法setBounds
中的大小 arguments。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Panel extends JFrame {
private ImageIcon FirstPageImage;
private JLabel FirstPageLabel;
private JLayeredPane SignupButtonLayer;
private JButton Button;
public Panel() {
setLayout(new FlowLayout());
FirstPageImage = new ImageIcon(getClass().getResource("FirstPageAnimationUsing.gif"));
FirstPageLabel = new JLabel(FirstPageImage);
FirstPageImage.setImage(FirstPageImage.getImage().getScaledInstance(343, 820, Image.SCALE_DEFAULT));
add(FirstPageLabel);
Button = new JButton();
SignupButtonLayer = new JLayeredPane();
SignupButtonLayer.setPreferredSize(new Dimension(160, 90));
// Button.setOpaque(true);
Button.setBackground(Color.cyan);
Button.setBounds(0, 0, 159, 82);
SignupButtonLayer.add(Button, JLayeredPane.DEFAULT_LAYER);
add(SignupButtonLayer);
}
public static void main(String[] args) {
Panel gui = new Panel();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setTitle("Reminder App");
// gui.setSize(360, 850);
gui.setVisible(true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.