I'm trying to move ImageIcon torrentIcon to the left side of JPanel jp, because it's located in the center of panel near the JLabel jl. Neither setBounds() nor setHorizontalTextPosition(), setVerticalTextPosition() methods didn't help with that. I also tried making it by adding torrenIcon to another imageL JLabel and moving by setLocation(), but it didn`t work too. What should I do then?
This is a code part of creating panel:
private static JPanel setPanel() {
JLabel jl = new JLabel("Авторизуйтесь на сумнівний сайт");
jl.setForeground(Color.white);
jl.setFont(new Font("Times New Roman", Font.PLAIN, 40));
ImageIcon torrentIcon = new ImageIcon("Icon.png");
Image im = torrentIcon.getImage().getScaledInstance(100,100, Image.SCALE_SMOOTH);
torrentIcon = new ImageIcon(im);
JLabel imageL = new JLabel();
imageL.setIcon(torrentIcon);
imageL.setHorizontalTextPosition(SwingConstants.LEFT);
imageL.setVerticalTextPosition(SwingConstants.CENTER);
jl.setHorizontalTextPosition(0);
jl.setVerticalTextPosition(0);
JPanel p = new JPanel();
p.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
p.setBackground(Color.RED);
p.add(imageL);
p.add(jl);
return p;
}
I took your code and created the following GUI.
Don't use
staticmethods with Swing.Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
When you type:
the default is a
FlowLayout. The Swing components will "flow" from left to right.Here's the same statement with all of the default values explicitly defined.
I read the icon from a URL, so anyone can run this code and get the same result.
Here's the complete runnable code. Save this so you can easily test different
JPanels.