Reputation: 73
I have a JFrame that is filled with is JPanel (code below).
I'm using the JPanel to draw stuff in it , for example i can draw lines anywhere however i like , but when adding JLabel to it i can't move it anywhere it is stuck in top center like this thread .
but the problem is the solution they suggested there doesn't work for me .
i tried adding :
getContentPane().setLayout(null);
sorry if i wasn't clear , i tried adding the above in the function initUI() before and after creating Surface.
but after that the frame shows with almost (1,1) size and its empty (if i manually resize it using mouse drag) .
this is my code :
WaveDrawerMain class
public class WaveDrawerMain extends JFrame {
private static WaveDrawerMain wd;
private Surface s;
public WaveDrawerMain() {
initUI();
s.drawLinexxx();
}
private void initUI() {
setupMenu();
s = new Surface(1200, 300);
add(s);
setTitle("Waves");
setSize(1200, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
private static void constructDrawer() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
wd = new WaveDrawerMain();
wd.setVisible(true);
}
});
}
public static WaveDrawerMain createDrawer(){
constructDrawer();
idPool = new IntPool(100);
lines = new LinesManager();
return wd;
}
}
Surface class:
class Surface extends JPanel {
private ArrayList<Integer> points = new ArrayList<Integer>();
private int pWidth, pHeight;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(pWidth, pHeight);
}
public Surface(int width, int height) {
pWidth = width;
pHeight = height;
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(30, 30, 200, 30);
for(int i = 0;i<points.size();i++){
g2d.drawLine(points.get(i), 100, points.get(i)+50, 100+50);
}
}
public void drawLinexxx(){
points.add(600);
JLabel lab1 = new JLabel("Test x "+Float.toString(getSize().width/3)+" y "+Float.toString(getSize().height/3));
lab1.setLocation(getSize().width/3, getSize().height/3);
add(lab1);
repaint();
}
}
Upvotes: 1
Views: 645
Reputation: 324108
but when adding JLabel to it i can't move it anywhere
The default layout manager for a JPanel
is a FlowLayout
. When you add components to the panel they are positioned based on the rules of the layout manager.
getContentPane().setLayout(null);
You don't want to set the content pane layout null, you want to set the Surface
panel layout to null.
However, when you do this you are now responsible for managing the functions of the layout manager which means once you add the label to the Surface panel you are responsible for setting the size and location of the label. The location and size will both default to (0, 0).
Upvotes: 1