There's a simple application that uses JScrollPane for 2 lists and have 1 button to switch them. I want to add many more Swing elements, but I cannot move them with object.setBounds. Whatever I will write in this method element doesn't change its place and size.
package paka;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;;
public class Question extends JFrame {
private JList leftlist,rightlist;
private JButton movebutton;
private JLabel pointlessLabel;
private static String[] foods={"bacon","wings","ham","beef","more bacon"};
public Question(){
super("title");
setLayout(new FlowLayout());
leftlist=new JList(foods);
leftlist.setVisibleRowCount(3);
leftlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(leftlist));
movebutton = new JButton("Move");
movebutton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
rightlist.setListData(leftlist.getSelectedValues());
}
}
);
add(movebutton);
rightlist = new JList();
rightlist.setVisibleRowCount(3);
rightlist.setFixedCellWidth(100);rightlist.setFixedCellHeight(15);
rightlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(rightlist));
//Okay, deleting everything below we have only two list with button that moves elements from 1st list to 2nd
movebutton = new JButton("Click me!");
movebutton.setBounds(700, 100, 80, 20);
add(movebutton);
pointlessLabel = new JLabel("I'm unbreakable");
pointlessLabel.setBounds(500,200,100,50);
add(pointlessLabel);
}
public static void main(String args[]){
Question go = new Question();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}
}
You need to use combinations of Layout Managers (as stated by @AndrewThompson on his comment above) to achieve the same output that you have with a
null layout.Avoid the use of
null layout, see: Null layout is evil and Why is it frowned upon to use a null layout in Swing?With the code below you can have the same output you had with
setBounds()method. I didn't added anActionListenerto this code, since I'm just demonstrating how to stop usingnull layoutand have the same output. Yes! The second one seems shorter, that's because ofpack()but you can stillsetSize()if you want / need an specific window size.To add more elements below just add more
JPanels and add them topane, I hope this helps to solve your issue, and if not, please post a Minimal Complete and Verifiable Example that we can copy-paste, make it short, but still shows your issue and follows above recommendationsImportant Note:
I'll bring a quote from This answer's comment of @MadProgrammer, because I used
prototypeCellValueto make therightList's width shorter: