目前,我想解决的问题是如何得到我的图像和按钮显示。
当我在代码中有以下行图像显示,但当我删除它我的图像不显示,但按钮: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
。 方法 - 不需要为
Button
显式调用setOpaque(true)
方法,因为这是默认的。 - 要么调用
pack()
——这通常是首选的——要么调用setSize()
,但不要同时调用。 setVisible(true)
应该只在GUI完全构建后调用。在下面的代码中,我在调用pack()
和setTitle()
之后调用它。- 我建议你尽量遵守Java的命名约定。
- 我还建议尽量不要将您的类命名为与JDK中的类相同。我指的是Panel。
setBounds
的参数——你在Button
上调用的——是相对于它的容器,即SignupButtonLayer
的。将x设置为94,将y设置为617表示将Button
放置在之外。SignupButtonLayer
的边界。所以你看不见它。在下面的代码中,我将x和y设置为0(零),以便Button
的左上角与SignupButtonLayer
的左上角对齐。下面的代码简单地解决了你的问题,即同时显示图像和按钮-同时使用FlowLayout
的[内容窗格]JFrame
。请注意,SignupButtonLayer
的首选大小略大于方法setBounds
中的size参数。
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);
}
}