[英]Picture and text in same window
This program is supposed to open a window, add a picture, and then add the text "hello world" above the picture. 该程序应该打开一个窗口,添加图片,然后在图片上方添加文本“ hello world”。 The text appears when i do frame.add(label) and then try to add the picture (like the code shows), but even when I do the opposite and add the picture first I only get a gray schreen. 当我执行frame.add(label)然后尝试添加图片(如代码所示)时,文本就会出现,但是即使我做了相反的操作并首先添加图片,我也只会看到灰色的schreen。 Can anybody show me how I can get both the picture and the text? 有人可以告诉我如何获得图片和文字吗?
public window(){
JFrame frame = new JFrame("name");
JLabel label = new JLabel ("hello world", JLabel.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(600, 400);
frame.setVisible(true);
label.setAlignmentX(0);
label.setAlignmentY(0);
frame.add(label);
frame.add(new JLabel(new ImageIcon("file")));;
}
}
You should use overlay
layout, but it is applicable on JPanel
. 您应该使用overlay
布局,但是它适用于JPanel
。
So add a JPanel
to your frame
then apply the layout
, finally add the components
. 因此,将JPanel
添加到frame
然后应用layout
,最后添加components
。
Your code may be like that: 您的代码可能像这样:
public window(){
JFrame frame = new JFrame("name");
JLabel label = new JLabel ("hello world", JLabel.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
public boolean isOptimizedDrawingEnabled() {
return false;
}
};
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
frame.setResizable(false);
frame.setSize(600, 400);
frame.setVisible(true);
label.setAlignmentX(0);
label.setAlignmentY(0);
panel.add(label);
panel.add(new JLabel(new ImageIcon("file")));
frame.add(panel, BorderLayout.CENTER);
}
}
A label can have both text and icon, and the relative position can be customized. 标签可以同时包含文本和图标,并且可以自定义相对位置。
JLabel label = new JLabel ("hello world", new ImageIcon("file"), JLabel.CENTER);
label.setVerticalTextPosition(SwingConstants.TOP);
frame.add(label);
//frame.add(new JLabel(new ImageIcon("file")));;
The default layout is BorderLayout, and add(label, BorderLayout.CENTER)
. 默认布局为BorderLayout和add(label, BorderLayout.CENTER)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.