How do you place objects in JPanel using BorderLayout?

I have the following class that implements 3 JPanels. 1 The panel has a label, then buttons, and the third is a table, as described in my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.event.*;

class  netTable implements ActionListener, TableModelListener
{
JFrame frame;
JTable table;
Vector rows,columns;
DefaultTableModel tabModel;
JScrollPane scrollPane;
JLabel lblMessage;
JButton cmdLookup, cmdUpdatePlan;
JPanel topPanel,mainPanel,buttonPanel;

public static void main(String[] args) 
    {
    netTable t=new netTable();
    }

netTable()
    {
    rows=new Vector();
    columns= new Vector();
    String[] columnNames = 
    { 
        "ID", 
        "Client",
        "Plan",
        "Amount"
    };

addColumns(columnNames);

tabModel=new DefaultTableModel();
tabModel.setDataVector(rows,columns);

table = new JTable(tabModel);
scrollPane= new JScrollPane(table);//ScrollPane

table.setRowSelectionAllowed(false);

table.getModel().addTableModelListener(this);

topPanel = new JPanel(); 
lblMessage=new JLabel("Invoices to Update"); 
topPanel.add(lblMessage); 

buttonPanel=new JPanel();

cmdLookup=new JButton("Lookup"); 
cmdUpdatePlan = new JButton("Update Plan");

buttonPanel.add(cmdLookup);
buttonPanel.add(cmdUpdatePlan);

cmdLookup.addActionListener(this);
cmdUpdatePlan.addActionListener(this);

mainPanel=new JPanel();
frame=new JFrame("Update Table");
frame.setSize(500,500);
frame.setExtendedState(JFrame.ICONIFIED);
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.NORTH);
mainPanel.add(buttonPanel,BorderLayout.CENTER);
mainPanel.add(scrollPane,BorderLayout.SOUTH);

topPanel.setBackground(Color.gray);
mainPanel.setBackground(Color.white);
buttonPanel.setBackground(Color.white);
table.getParent().setBackground(Color.black);
frame.getContentPane().add(mainPanel);
frame.addWindowListener(new WindowCloser());
frame.setVisible(true);
}

}

When I compile this, it displays the ButtonPanel button at the top, a space and then scroll below it, leaving a mark where the topPanel should appear first at the top. Any ideas? I think the position of BorderLayout is wrong.

+3
source share
3 answers

There is no space for these panels, so the top panel shrinks by about 3 pixels. Try

frame.setSize(800,800);

instead.

+1
source

The problem is this line:

frame.setExtendedState(JFrame.ICONIFIED);

- , , topPanel .

:

  • try, , .

  • () , ( ). , frame.setVisible(true);, .

+1

. , "" , JPanel , mainPanel

0

Source: https://habr.com/ru/post/1730287/


All Articles