我创建了这个代码来使用图标作为背景进行Q& A事情:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class test
{
private JFrame frame;
private JLabel label;
private JLabel bg;
private Jbutton button1;
private ImageIcon icon;
private JTextField tf;
public test(){
run();
}
public void run(){
frame = new JFrame("Test");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
icon = new ImageIcon("My_Path");
bg = new JLabel(icon);
bg.setLayout(new FlowLayout());
frame.getContentPane().setLayout(new FlowLayout());
tf = new JTextField("text field",100);
tf.setHorizontalAlignment(JTextField.CENTER);
frame.getContentPane().add(tf);
button1 = new JButton("Check!");
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
/*action*/
}
});
frame.add(bg);
label = new JLabel("text");
bg.add(label);
bg.add(button1);
}
public void main(String[] args){
new test();
}
由于某种原因,文本字段“阻止”标签bg并使其移动。 如何让文本字段“覆盖”标签bg中的图标?
答案 0 :(得分:0)
您可能需要指定布局,以便按照您希望的方式放置元素。例如:您可以将布局设置为null
frame.setLayout(空);
并使用setBounds(x,x,x,x)指定对象的坐标,或者使用任何其他布局,这一切都取决于你需要它们......
查看此内容以获取更多参考资料......
http://www.javatpoint.com/java-layout-manager
https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
答案 1 :(得分:0)
您可以创建自定义JPanel并覆盖其paintComponent方法,但通常更容易使用OverlayLayout:
JComponent fields = new JPanel(new GridBagLayout());
fields.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.BASELINE_LEADING;
fields.add(tf, gbc);
gbc.insets.top = 6;
fields.add(label, gbc);
fields.add(button1, gbc);
fields.setAlignmentX(JComponent.CENTER_ALIGNMENT);
fields.setAlignmentY(JComponent.CENTER_ALIGNMENT);
bg.setAlignmentX(JComponent.CENTER_ALIGNMENT);
bg.setAlignmentY(JComponent.CENTER_ALIGNMENT);
JPanel overlay = new JPanel();
overlay.setLayout(new OverlayLayout(overlay));
overlay.add(fields);
overlay.add(bg);
frame.getContentPane().add(overlay);
请注意,在向JFrame添加组件后,您应该致电frame.setVisible(true)
。