I have set location (0,0) for the JLabel with respect to the JPanel. But it is appering at the center and top. What mistake am I making ?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Main extends JFrame
{
private JPanel panel;
private JLabel label1;
public Main()
{
panel = new JPanel();
panel.setBackground(Color.YELLOW);
ImageIcon icon1 = new ImageIcon("3.png");
label1 = new JLabel(icon1);
label1.setLocation(0,0);
panel.add(label1);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(panel);
this.setSize(500,500);
this.setVisible(true);
}
public static void main (String[] args) {
new Main();
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.URL;
public class Main extends JFrame
{
private JPanel panel;
private JLabel label1;
public Main() throws Exception
{
// Do use layouts (with padding & borders where needed)!
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.setBackground(Color.YELLOW);
URL url = new URL("http://pscode.org/media/starzoom-thumb.gif");
ImageIcon icon1 = new ImageIcon(url);
label1 = new JLabel(icon1);
// Don't use null layouts, setLocation or setBounds!
//label1.setLocation(0,0);
panel.add(label1);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(panel);
setSize(400,200);
setLocationByPlatform(true);
setVisible(true);
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new Main();
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
}
There seems to be a lot of confusion amongst replies to this thread, so to clarify one matter:
JPanel
does have a FlowLayout
by default. FlowLayout
it gets, comes from the 'no args' constructor, e.g. new FlowLayout()
1. FlowLayout
produces..
(1) ..a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With