如何使用BorderLayout在JPanel中定位对象?

时间:2010-01-27 22:27:35

标签: java jframe jpanel

我有以下类实现3个JPanel。 1面板有一个标签,下面是按钮,第三个是我的代码中描述的表:

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);
}

}

当我编译它时,它会在顶部显示一个buttonPanel,一个空格,然后在它下方显示scrollPane,省去topPanel应首先显示在顶部的标签。有任何想法吗?我认为BorderLayout的位置是错误的。

3 个答案:

答案 0 :(得分:1)

这些面板没有空间,因此顶部面板被压缩成约3个像素。尝试

frame.setSize(800,800);

代替。

答案 1 :(得分:1)

问题似乎是这一行:

frame.setExtendedState(JFrame.ICONIFIED);

出于某种原因,如果在将组件添加到框架之前运行,则topPanel将消失。

您可以执行以下操作之一:

  1. 将整个构造函数放入try块中,最后设置扩展状态。

  2. (推荐)在构造完所有内容后设置扩展状态(使用其他方法或直接在main中)。您还应该将frame.setVisible(true);之类的内容移动到这样的方法中。

答案 2 :(得分:0)

中心小组将eat as much of the available space as possible。如果要使用顶部标签和滚动窗格之间的按钮“最大化”滚动窗格,请创建另一个带边框布局的JPanel,向北添加按钮并将窗格滚动到中心,然后将整个面板添加到中心你的mainPanel