How to set layout in java GUI swing? - java

I am trying to create a register form for my application(school project), I wanted to set the layout to BoxLayout but the Jtextfields and combo box is having issue as you can see below, does this issue relates to setSize() or is it something I am doing incorrect,I just want the Jtextfields sorts vertically , I appreciate the support
private JPanel SetUpRegister() {
JLabel registerLabel = new JLabel("Registera");
registerLabel.setFont(new Font("Arial", Font.BOLD, 30));
loginRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
passwordRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
fnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
lnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
ageRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
String[] genderlist = new String[] { "Male", "Female", "Other" };
JComboBox<String> registerList = new JComboBox<>(genderlist);
JPanel registerPanel = new JPanel();
registerPanel.setBackground(new Color(255, 140, 0));
registerPanel.add(registerLabel);
registerPanel.add(loginRegisterInput);
registerPanel.add(passwordRegisterInput);
registerPanel.add(fnRegisterInput);
registerPanel.add(lnRegisterInput);
registerPanel.add(ageRegisterInput);
registerPanel.add(registerList);
registerPanel.setLayout(new BoxLayout(registerPanel,BoxLayout.Y_AXIS));
return registerPanel;
}

The input fields are huge
The BoxLayout will attempt to resize components when extra space is available on the panel. It will resize a component up to its maximum size.
For some reason the maximum height of a JTextField is Integer.MAX_VALUE which makes no sense to me, since the height of the text never changes as you enter more text.
In any case you have a couple of choices:
Use a different layout manager, like the GridBagLayout. The GridBagLayout, will respect the preferred size of the text fields.
Create a custom JTestField and override the getMaximumSize() method to return the preferred height of the component
Use a wrapper panel.
For the wrapper panel you could do:
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(registerPanel, BorderLayout.PAGE_START);
return wrapper;
//return registerPanel;
The BorderLayout will respect the preferred height of any component added to the PAGE_START, so there is no need for the BoxLayout to resize any component.

private JPanel SetUpRegister() {
JLabel registerLabel = new JLabel("Registera");
JLabel registerLabel1 = new JLabel("Login :");
JLabel registerLabel2 = new JLabel("Password :");
JLabel registerLabel3 = new JLabel("First Name :");
JLabel registerLabel4 = new JLabel("Last Name :");
JLabel registerLabel5 = new JLabel("Age :");
JLabel registerLabel6 = new JLabel("Gender :");
JLabel registerLabel7 = new JLabel("Bio :");
registerLabel.setFont(new Font("Arial", Font.BOLD, 30));
JButton createAccButton = new JButton("Create");
createAccButton.addActionListener(new CreateAccountListener());
loginRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
passwordRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
fnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
lnRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
ageRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
bioRegisterInput = new JTextField(INPUT_FIELD_WIDTH);
String[] genderlist = new String[] { "Male", "Female", "Other" };
registerList = new JComboBox(genderlist);
JPanel registerPanel = new JPanel();
registerPanel.setLayout(new BoxLayout(registerPanel, BoxLayout.Y_AXIS));
registerPanel.add(registerLabel);
JPanel registerLabPanel = new JPanel();
registerLabPanel.setLayout(new FlowLayout());
registerLabPanel.add(registerLabel);
JPanel usernamePanel = new JPanel();
usernamePanel.setLayout(new FlowLayout());
usernamePanel.add(registerLabel1);
usernamePanel.add(loginRegisterInput);
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout(new FlowLayout());
passwordPanel.add(registerLabel2);
passwordPanel.add(passwordRegisterInput);
JPanel fnPanel = new JPanel();
fnPanel.setLayout(new FlowLayout());
fnPanel.add(registerLabel3);
fnPanel.add(fnRegisterInput);
JPanel lnPanel = new JPanel();
lnPanel.setLayout(new FlowLayout());
lnPanel.add(registerLabel4);
lnPanel.add(lnRegisterInput);
JPanel agePanel = new JPanel();
agePanel.setLayout(new FlowLayout());
agePanel.add(registerLabel5);
agePanel.add(ageRegisterInput);
JPanel genderPanel = new JPanel();
genderPanel.setLayout(new FlowLayout());
genderPanel.add(registerLabel6);
genderPanel.add(registerList);
JPanel bioPanel = new JPanel();
bioPanel.setLayout(new FlowLayout());
bioPanel.add(registerLabel7);
bioPanel.add(bioRegisterInput);
JPanel buttonLoginPanel = new JPanel();
buttonLoginPanel.setLayout(new FlowLayout());
buttonLoginPanel.add(createAccButton);
registerPanel.add(registerLabel);
registerPanel.add(usernamePanel);
registerPanel.add(passwordPanel);
registerPanel.add(fnPanel);
registerPanel.add(lnPanel);
registerPanel.add(agePanel);
registerPanel.add(genderPanel);
registerPanel.add(bioPanel);
registerPanel.add(buttonLoginPanel);
return registerPanel;
}
I fixed the issue by making a Panel for each input and label

Related

Java GUI Fill Empty spaces

I have the following Java GUI for my project. For some reason, the middle and right panels have been put below leaving empty spaces - marked in red. Is there a way to pull the panels up to fill the spaces.
These empty spaces does not look good. I have tried to check all code but cannot pinpoint where to correct.
Thanks in advance.
public static JPanel main= new JPanel(),
left= new JPanel(),middle= new JPanel(),right = new JPanel();
Container c = getContentPane();
c.setLayout(new FlowLayout()) ;
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(new JLabel("Enter word/SQL: "), "North");
pane.add(tf, "Center"); //enter keyword
JPanel second = new JPanel();
second.setLayout(new GridLayout(8, 1));
second.add(messageIDText);
//This is the start of adding panels
//create a left side panal and add the sub panels to it
JPanel left = new JPanel();
JPanel middle = new JPanel();
JPanel center = new JPanel();
JTextArea output = new JTextArea("", 60, 60);
JPanel sixth = new JPanel();
JPanel seventh = new JPanel();
JPanel eigth = new JPanel(new GridLayout(8,1));
JPanel labels7 = new JPanel(new GridLayout(5,1));
JPanel controls7 = new JPanel(new GridLayout(5,1));
JPanel tenth = new JPanel();
sixth.setLayout(new BorderLayout(5,5));
JPanel fourth = new JPanel();
fourth.add(firstButton);
sixth.add(labels, BorderLayout.WEST);
sixth.add(controls, BorderLayout.CENTER);
sixth.add(controlsButtons, BorderLayout.EAST);
labels.add(new JLabel("Proposal:"));
controls.add(proposalNumberText);
controlsButtons.add(freeQueryButton);
//add border
pane.setBorder(BorderFactory.createCompoundBorder(new
EmptyBorder(10,10,10,10), BorderFactory.createEtchedBorder()));
fourth.setBorder(BorderFactory.createCompoundBorder(new
EmptyBorder(10,10,10,10), BorderFactory.createEtchedBorder()));
//-------LEFT SIDE -- PARAMETERS
left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
JLabel headerLabel,blank;
headerLabel = new JLabel("Navigate Records", JLabel.LEFT);
Font f = headerLabel.getFont();
headerLabel.setFont(f.deriveFont(f.getStyle() ^ Font.BOLD)); // bold
left.add(headerLabel, BorderLayout.PAGE_END);
left.add(fourth, BorderLayout.PAGE_END);
main.add(left);
//---------MIDDLE PART - Messages - tabbed pane
JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
//jtp.setSize(jtp.getPreferredSize());
JPanel jpA = new JPanel(),jpB = new JPanel(),
jpC = new JPanel(),jpD = new JPanel();
JScrollPane scrollPane2 = new JScrollPane(),jp = new
JScrollPane(activeTSText), jp2 = new JScrollPane(analyseWordsText),
jp3 = new JScrollPane(markedMessageText);
JLabel labelA = new JLabel();
labelA.setText("");
jpA.add(labelA);
jpA.add(jp);
jtp.addTab("Message", jpA);
middle.add(jtp);
main.add(middle);
//----------RIGHT PART - .. //paramters and results
JPanel jj = new JPanel();
jj.setLayout(new BoxLayout(jj, BoxLayout.PAGE_AXIS));
stateJTable.setRowHeight(20); //add JTable
JScrollPane js3 =new JScrollPane(stateJTable);
js3.setVisible(true);
//JTabbedPane jtp2 = new JTabbedPane();
//JPanel StateSubstatesTabOnLeft = new JPanel(),
StateSubstates_PostProcessedTabOnLeft = new JPanel();
JPanel firstleftTabinRightSideOfFrame = new JPanel(),
secondLeftTabinRightSideOfFrame = new
JPanel(),rightTabInRightSideOfFrame = new JPanel();
jj.add(js3);
//downbelow, the state jtable is added to the panel here through the
//scrollpane which contains the jtable
right.add(jj) ; //stateJTable);// add table in panel using add() method
main.add(right);
proposalNumberText.requestFocusInWindow();
I have solved the problem by using Borderlayout and assigning the main panel to it.
The assigning the WEST, CENTER and EAST regions to it.
I have added the code below in the code above at places where the main panel is being added to.
Thank you for the advice to start debugging by using MRE approach.
BorderLayout layout = new BorderLayout();
main.setLayout(layout);
main.add(left,BorderLayout.WEST);
main.add(middle,BorderLayout.CENTER);
main.add(right,BorderLayout.EAST);

JFreeChart hide behind other one

I was trying to build UI in IntelliJ but it was hard so I tried to build it in Eclipse. Now UI looks little better but still poor. One of chart (the cener one) should be biger and second one on south should be smaller but flat and long. I tried to use preffered size or validate or repaint but still nothing. How to anchor them to side borders, and avoid to cover them self?
public class MainWindow extends JFrame{
private JPanel contentPane;
private XYSeries daneXYSciezki;
private XYSeries daneXYWys;
private final XYSeriesCollection wykCenter;
private final XYSeriesCollection wykSouth;
public MainWindow(){
setTitle("ParserGPS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 880, 640);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panelNorth = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelNorth.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panelNorth, BorderLayout.NORTH);
JButton btnWczytajPlik = new JButton("Wczytaj plik");
panelNorth.add(btnWczytajPlik);
JLabel lblOdlego = new JLabel("Odległość:");
panelNorth.add(lblOdlego);
JLabel lblm = new JLabel("0m");
panelNorth.add(lblm);
JLabel lblCzas = new JLabel("Czas:");
panelNorth.add(lblCzas);
JLabel label = new JLabel("00:00:00");
panelNorth.add(label);
JLabel lblPrdko = new JLabel("Prędkość:");
panelNorth.add(lblPrdko);
JLabel lblkmh = new JLabel("0km/h");
panelNorth.add(lblkmh);
JLabel lblNrSat = new JLabel("Nr sat:");
panelNorth.add(lblNrSat);
JLabel label_1 = new JLabel("0");
panelNorth.add(label_1);
JLabel lblGga = new JLabel("GGA:");
lblGga.setHorizontalAlignment(SwingConstants.CENTER);
panelNorth.add(lblGga);
JLabel label_2 = new JLabel("0/0");
panelNorth.add(label_2);
JLabel lblGsa = new JLabel("GSA:");
panelNorth.add(lblGsa);
JLabel label_3 = new JLabel("0/0");
panelNorth.add(label_3);
JLabel lblNewLabel = new JLabel("RMC:");
panelNorth.add(lblNewLabel);
JLabel label_4 = new JLabel("0/0");
panelNorth.add(label_4);
JLabel lblGll = new JLabel("GLL:");
panelNorth.add(lblGll);
JLabel label_5 = new JLabel("0/0");
panelNorth.add(label_5);
JLabel lblVtg = new JLabel("VTG:");
panelNorth.add(lblVtg);
JLabel label_6 = new JLabel("0/0");
panelNorth.add(label_6);
JPanel jpCenter = new JPanel();
contentPane.add(jpCenter, BorderLayout.CENTER);
jpCenter.setPreferredSize(new Dimension(785, 440));
JPanel jpSouth = new JPanel();
FlowLayout flowLayout_1 = (FlowLayout) jpSouth.getLayout();
flowLayout_1.setAlignment(FlowLayout.TRAILING);
contentPane.add(jpSouth, BorderLayout.SOUTH);
this.daneXYSciezki = new XYSeries("Trasa", false);
wykCenter = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykCenter = createChart(wykCenter);
final ChartPanel jfcPanelCenter = new ChartPanel(jfcWykCenter);
jpCenter.add(jfcPanelCenter,BorderLayout.CENTER);
this.daneXYSciezki = new XYSeries("Wysokość", false);
wykSouth = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykSouth = createChart(wykSouth);
final ChartPanel jfcPanelSouth = new ChartPanel(jfcWykSouth);
jpSouth.add(jfcPanelSouth,BorderLayout.CENTER);
repaint();
revalidate();
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createXYLineChart(
"",
"Szerokość",
"Długość",
dataset);
final XYPlot plot = result.getXYPlot();
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
yAxis.setAutoRangeIncludesZero(false);
yAxis.setAutoRange(true);
customizeChart(result);
return result;
}
private void customizeChart(JFreeChart chart) {
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer;
renderer = new XYLineAndShapeRenderer(true, true);
renderer.setSeriesShapesVisible(0, true);
renderer.setSeriesShapesVisible(1, false);
renderer.setSeriesPaint(0, Color.RED);
renderer.setSeriesStroke(0, new BasicStroke(1.0f));
plot.setRenderer(renderer);
plot.setBackgroundPaint(Color.WHITE);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.BLACK);
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.BLACK);
}
}
After #m.cekiera advices
public class MainWindow extends JFrame{
private JPanel contentPane;
private XYSeries daneXYSciezki;
private XYSeries daneXYWys;
private final XYSeriesCollection wykCenter;
private final XYSeriesCollection wykSouth;
public MainWindow(){
setTitle("ParserGPS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 880, 640);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panelNorth = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelNorth.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(panelNorth,BorderLayout.NORTH);
JButton btnWczytajPlik = new JButton("Wczytaj plik");
panelNorth.add(btnWczytajPlik);
JLabel lblOdlego = new JLabel("Odległość:");
panelNorth.add(lblOdlego);
JLabel lblm = new JLabel("0m");
panelNorth.add(lblm);
JLabel lblCzas = new JLabel("Czas:");
panelNorth.add(lblCzas);
JLabel label = new JLabel("00:00:00");
panelNorth.add(label);
JLabel lblPrdko = new JLabel("Prędkość:");
panelNorth.add(lblPrdko);
JLabel lblkmh = new JLabel("0km/h");
panelNorth.add(lblkmh);
JLabel lblNrSat = new JLabel("Nr sat:");
panelNorth.add(lblNrSat);
JLabel label_1 = new JLabel("0");
panelNorth.add(label_1);
JLabel lblGga = new JLabel("GGA:");
//lblGga.setHorizontalAlignment(SwingConstants.CENTER);
panelNorth.add(lblGga);
JLabel label_2 = new JLabel("0/0");
panelNorth.add(label_2);
JLabel lblGsa = new JLabel("GSA:");
panelNorth.add(lblGsa);
JLabel label_3 = new JLabel("0/0");
panelNorth.add(label_3);
JLabel lblNewLabel = new JLabel("RMC:");
panelNorth.add(lblNewLabel);
JLabel label_4 = new JLabel("0/0");
panelNorth.add(label_4);
JLabel lblGll = new JLabel("GLL:");
panelNorth.add(lblGll);
JLabel label_5 = new JLabel("0/0");
panelNorth.add(label_5);
JLabel lblVtg = new JLabel("VTG:");
panelNorth.add(lblVtg);
JLabel label_6 = new JLabel("0/0");
panelNorth.add(label_6);
JPanel jpCenter = new JPanel(new BorderLayout());
contentPane.add(jpCenter, BorderLayout.CENTER);
//jpCenter.setPreferredSize(new Dimension(785, 440));
JPanel jpSouth = new JPanel(new BorderLayout());
//FlowLayout flowLayout_1 = (FlowLayout) jpSouth.getLayout();
// flowLayout_1.setAlignment(FlowLayout.TRAILING);
contentPane.add(jpSouth, BorderLayout.SOUTH);
this.daneXYSciezki = new XYSeries("Trasa", false);
wykCenter = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykCenter = createChart(wykCenter);
final ChartPanel jfcPanelCenter = new ChartPanel(jfcWykCenter);
jpCenter.add(jfcPanelCenter,BorderLayout.NORTH);
this.daneXYSciezki = new XYSeries("Wysokość", false);
wykSouth = new XYSeriesCollection(this.daneXYSciezki);
final JFreeChart jfcWykSouth = createChart(wykSouth);
final ChartPanel jfcPanelSouth = new ChartPanel(jfcWykSouth);
jpCenter.add(jfcPanelSouth,BorderLayout.SOUTH);
}
...
}
As your code is not MCVE I could not run it with changes, but I think your problem is bad layout settings. For example, you create a new JPanel:
JPanel jpSouth = new JPanel();
FlowLayout flowLayout_1 = (FlowLayout) jpSouth.getLayout();
flowLayout_1.setAlignment(FlowLayout.TRAILING);
You are aware that it is using FlowLayout by defaul, by later you use:
jpSouth.add(jfcPanelSouth,BorderLayout.CENTER);
but you never change layout to BorderLayout. You cannot mix layout of one particular container. But this is not what couse you problem directly.
Your BorderLayout.SOUTH area stretch horizontally, to fit components inside, and BorderLayout.CENTER takes all spece left(or not). This is how those parts of BorderLayout works. So you can change where you put particular components, or change layout at all.
I suggest to try with:
JPanel jpCenter = new JPanel(new BorderLayout());
...
jpCenter.add(jfcPanelCenter,BorderLayout.NORTH);
...
jpCenter.add(jfcPanelSouth,BorderLayout.SOUTH); //not to contentPane!
this will change an arrangement. However I am not sure, is it what you want. If not, try with different layout, for example BoxLayout.
Also I would rather use pack() and set size of components, than setBounds on a countainer.
You can also use GUI builders, like Netbeans IDE GUI Builder if you want to create GUI but don't care how.

Java scrollbar not visible

I am new to java. I am trying to implement scroll feature to my Jpanel but the schoolpane is not visible. I tried to many methods but nothing works.
public class test extends ContentPanel {
JPanel secondary;
JPanel customerType;
JPanel primary;
JPanel labelPanel;
JLabel lCustNo;
JLabel lCustName;
JLabel lTelNo;
JLabel lAddress;
JLabel lNationality;
JLabel lResident;
JLabel lVisitor;
JLabel lCustomerType;
JLabel lIdCard;
JLabel lBankName;
JLabel lPassportNo;
JLabel lVisitStart;
JLabel lVisitEnd;
JTextField tCustNo;
JTextField tCustName;
JTextField tTelNo;
JTextField tAddress;
JTextField tNationality;
JTextField tIdCard;
JTextField tBankName;
JTextField tPassportNo;
JTextField tVisitStart;
JTextField tVisitEnd;
JPanel radioButton;
JRadioButton rResident;
JRadioButton rVisitor;
ButtonGroup custType;
JScrollPane scrollBar;
JSeparator s1;
public test (String title, JPanel parent) {
super(title, parent);
secondary = new JPanel(new GridLayout(2,0));
secondary.setBounds(10, 10, 500, 800);
labelPanel = new JPanel(new GridLayout(5,2,300,20));
radioButton = new JPanel(new GridLayout(1, 4));
customerType = new JPanel(new GridLayout(3,4, 30, 20));
primary = new JPanel(new BorderLayout());
lCustNo = new JLabel("Customer No: ");
lCustName = new JLabel("Name: ");
lTelNo = new JLabel("Telephone Number: ");
lAddress = new JLabel("Address: ");
lNationality = new JLabel("Nationality: ");
lResident = new JLabel("Resident");
lVisitor = new JLabel("Visitor");
lCustomerType = new JLabel("Customer Type");
lIdCard = new JLabel("Id Card");
lBankName = new JLabel("Bank Name");
lPassportNo = new JLabel("Passport Number");
lVisitStart = new JLabel("Visit Start");
lVisitEnd = new JLabel("Visit End");
tCustNo = new JTextField(10);
tCustName = new JTextField(10);
tTelNo = new JTextField(10);
tAddress = new JTextField(10);
tNationality = new JTextField(10);
tIdCard = new JTextField(10);
tBankName = new JTextField(10);
tPassportNo = new JTextField(10);
tVisitStart = new JTextField(10);
tVisitEnd = new JTextField(10);
rResident = new JRadioButton();
rVisitor = new JRadioButton();
custType = new ButtonGroup();
customerType.add(lPassportNo);
customerType.add(tPassportNo);
customerType.add(lVisitStart);
customerType.add(tVisitStart);
customerType.add(lIdCard);
customerType.add(tIdCard);
customerType.add(lBankName);
customerType.add(tBankName);
customerType.add(lVisitEnd);
customerType.add(tVisitEnd);
custType.add(rResident);
custType.add(rVisitor);
radioButton.add(lVisitor);
radioButton.add(rVisitor);
radioButton.add(lResident);
radioButton.add(rResident);
labelPanel.add(lCustNo);
labelPanel.add(tCustNo);
labelPanel.add(lCustName);
labelPanel.add(tCustName);
labelPanel.add(lTelNo);
labelPanel.add(tTelNo);
labelPanel.add(lAddress);
labelPanel.add(tAddress);
labelPanel.add(lNationality);
labelPanel.add(tNationality);
secondary.add(customerType);
secondary.add(labelPanel);;
primary.add(secondary,BorderLayout.CENTER);
scrollBar= new JScrollPane(primary);
scrollBar.setBounds(10, 10, 400, 555);
this.add(scrollBar);
}
}
My code is above. This class extends contentPanel and contentPanel extends JPanel. Someone please help me.
Thanks.
Your scrollBar is not visible because it is not necessary. If you change JScrollPane settings, for example:
scrollBar.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
you will see you have it, but not use it. It is because your scrollBar doesn't have a content which expands dynamically (like JTextArea for example). Your scrollBar has JPanel inside, which has size to fit all its components, so it will not be enough to add some text inside text components.
To make scroll bars visible, you can change a size of JSrollPane. However setBound() will not work if you JPanel use default FlowLayout. To use absolute positioning in JPanel you need to use null layout, what is generally not recommended and is seen as bad programming practice.
Try to delete setBound() lines and use for example scrollBar.setPreferredSize(new Dimension(400,555)); instead. You should see a difference.

How to add multiple JPanels to JFrame with different sizes

I tried to do this from stackoverflow:
adding multiple jPanels to jFrame
But that didn't seem to work out like in the example, could anyone tell me what im doing wrong?
Im trying to add multiple JPanels with each their own sizes to the JFrame. I was also hoping it was possible to give each JPanel specific sizes and ability to put them on the exact spot i want.
Picture of what i try to make:
This is my code so far:
public ReserveringenGUI(ReserveringController controller) {
this.controller = new ReserveringController();
makeFrame();
}
public void makeFrame() {
JFrame frame1 = new JFrame();
frame1.setTitle("Reserveringen");
frame1.setSize(800, 500);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
JPanel willekeurigPanel = new JPanel();
willekeurigPanel.setSize(400, 500);
willekeurigPanel.setBackground(Color.YELLOW);
willekeurigPanel.setVisible(true);
JPanel overzichtPanel = new JPanel();
overzichtPanel.setSize(400, 500);
overzichtPanel.setBackground(Color.red);
overzichtPanel.setVisible(true);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
DateFormatter df = new DateFormatter(format);
JFormattedTextField dateBeginField = new JFormattedTextField(df);
dateBeginField.setPreferredSize(new Dimension(250, 20));
dateBeginField.setValue(new Date());
JFormattedTextField dateEndField = new JFormattedTextField(df);
dateEndField.setPreferredSize(new Dimension(250, 20));
dateEndField.setValue(new Date());
JTextField klantnummer = new JTextField();
klantnummer.setPreferredSize(new Dimension(250, 20));
JTextField artikelnummer = new JTextField();
artikelnummer.setPreferredSize(new Dimension(250, 20));
JLabel dateBeginLabel = new JLabel("Begin Datum ");
JLabel dateEndLabel = new JLabel("Eind datum: ");
JLabel klantID = new JLabel("Klant nummer: ");
JLabel artikelID = new JLabel("Artikel nummer: ");
JButton voegReserveringToe = new JButton("Voeg toe");
voegReserveringToe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
voegReserveringToeActionPerformed(evt);
}
});
willekeurigPanel.add(dateBeginLabel);
willekeurigPanel.add(dateBeginField);
willekeurigPanel.add(dateEndLabel);
willekeurigPanel.add(dateEndField);
willekeurigPanel.add(klantID);
willekeurigPanel.add(klantnummer);
willekeurigPanel.add(artikelID);
willekeurigPanel.add(artikelnummer);
willekeurigPanel.add(voegReserveringToe);
container.add(willekeurigPanel);
container.add(overzichtPanel);
frame1.add(container);
frame1.setVisible(true);
}
As discussed here, don't set the size and position of components arbitrarily. Instead, let the layout do the work, nesting as required. Use the GroupLayout shown here for the labeled input fields. Add each to the CENTER of a panel having BorderLayout, with a button in the SOUTH on the left. Finally, add both panels to an enclosing panel having GridLayout(1, 0).

JPanel GridLayout not adding components

I am trying to create a GUI using JPanels that have a GridLayout. The fromPanel works perfectly, but the toPanel will only add the JTextFields. The code for the panels is almost exactly the same so I'm not sure why one works but the other doesn't. I have tried changing either rows or columns to 0, but the JLabels still don't show up in the toPanel.
Here is my code:
public class Driver extends JFrame{
private int WIDTH = 800, HEIGHT = 500, WIDTH2 = 350;
private JPanel toPanel, fromPanel, sizePanel, messagePanel, deliveryPanel,
totalPanel, bottomPanel;
private JLabel firstLabel, lastLabel, streetLabel, cityLabel, stateLabel, zipLabel;
private JTextField toFirstText, toLastText, toStreetText, toCityText, toStateText, toZipText,
fromFirstText, fromLastText, fromStreetText, fromCityText, fromStateText, fromZipText;
public Driver(){
setTitle("JoAnn's Floral");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
//labels
lastLabel = new JLabel("Last Name", JLabel.RIGHT);
firstLabel = new JLabel("First Name", JLabel.RIGHT);
streetLabel = new JLabel("Street", JLabel.RIGHT);
cityLabel = new JLabel("City", JLabel.RIGHT);
stateLabel = new JLabel("State", JLabel.RIGHT);
zipLabel = new JLabel("ZIP", JLabel.RIGHT);
buildToPanel();
add(toPanel);
buildFromPanel();
add(fromPanel);
}
public void buildToPanel(){
toPanel = new JPanel(new GridLayout(6, 2, 5, 5));
toPanel.setBorder(BorderFactory.createTitledBorder("To"));
toPanel.setPreferredSize(new Dimension(WIDTH2, HEIGHT/3));
//text fields
toLastText = new JTextField(10);
toFirstText = new JTextField(10);
toStreetText = new JTextField(10);
toCityText = new JTextField(10);
toStateText = new JTextField(10);
toZipText = new JTextField(10);
//add to layout
toPanel.add(firstLabel);
toPanel.add(toFirstText);
toPanel.add(lastLabel);
toPanel.add(toLastText);
toPanel.add(streetLabel);
toPanel.add(toStreetText);
toPanel.add(cityLabel);
toPanel.add(toCityText);
toPanel.add(stateLabel);
toPanel.add(toStateText);
toPanel.add(zipLabel);
toPanel.add(toZipText);
}
public void buildFromPanel(){
fromPanel = new JPanel(new GridLayout(6, 2, 5, 5));
fromPanel.setBorder(BorderFactory.createTitledBorder("From"));
fromPanel.setPreferredSize(new Dimension(WIDTH2, HEIGHT/3));
//text fields
fromFirstText = new JTextField(10);
fromLastText = new JTextField(10);
fromStreetText = new JTextField(10);
fromCityText = new JTextField(10);
fromStateText = new JTextField(10);
fromZipText = new JTextField(10);
//add to layout
fromPanel.add(firstLabel);
fromPanel.add(fromFirstText);
fromPanel.add(lastLabel);
fromPanel.add(fromLastText);
fromPanel.add(streetLabel);
fromPanel.add(fromStreetText);
fromPanel.add(cityLabel);
fromPanel.add(fromCityText);
fromPanel.add(stateLabel);
fromPanel.add(fromStateText);
fromPanel.add(zipLabel);
fromPanel.add(fromZipText);
}
public static void main(String[] args) {
Driver drive = new Driver();
drive.setVisible(true);
}
}
A JComponent can only appear in one container at a time. Since there is only one instance of each label, the code will only show one on-screen.
Tips
See Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (Yes.)
Also consider GroupLayout for each detail panel as seen in this answer.

Categories