每当我将面板的布局设置为FlowLayout时,都会出现JTable,但是我的imageBackground和按钮却放错了位置。当我将布局设置为null时,表格不会出现,但是按钮和imageBackground是我想要的位置。我要怎么办?

public class AssetPanel extends JPanel implements ActionListener{
    private ArrayList<AssetDetails> assetList;
    private Frame frame;
    private Database db;

    private JTable assetTable;
    private JScrollPane scrollPane;

    private JButton btnBack;
    private JButton btnView;

    public AssetPanel (Frame frame){
        super();
        this.frame = frame;
        initialize();
    }

    public void initialize(){
        setName("Assets");
        setSize(700, 475);
        setLayout(null);
        setVisible(true);

        db = new Database();

        btnView = new JButton("View");
        btnView.addActionListener(this);
        btnView.setBounds(450, 400, 90, 20);
        add(btnView);

        btnBack = new JButton("Back");
        btnBack.setFont(new Font("Tahoma", Font.BOLD, 12));
        btnBack.setBounds(550, 400, 90, 20);
        btnBack.addActionListener(this);
        add(btnBack);

        ImageIcon imageBackground = new ImageIcon(AssetPanel.class.getResource("/resources/assets.png"));
        JLabel jlBackground  = new JLabel(imageBackground);
        jlBackground.setBounds(0,0, 700, 475);
        add(jlBackground);
        initializeTable();
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if(ae.getSource() == btnBack){
            frame.changePanel("Main Menu");
        }
    }

    public void initializeTable(){
        Object[][] assetData;
        assetList = new ArrayList<>();
        String[] columnNames = {"Asset Name", "Date Acquired", "Type", "Classification"};
        assetList = db.getAssetTable();

        assetData = new Object[assetList.size()][columnNames.length];
        for(int i = 0; i < assetList.size(); i++){
            assetData[i][0] = assetList.get(i).getAssetName();
            assetData[i][1] = assetList.get(i).getDateAcquired();
            assetData[i][2] = assetList.get(i).getType();
            assetData[i][3] = assetList.get(i).getClassification();
        }

        assetTable = new JTable(assetData, columnNames);
        assetTable.setPreferredScrollableViewportSize(new Dimension(400, 100));
        assetTable.setLocation(150, 100);
        assetTable.setFillsViewportHeight(true);

        scrollPane = new JScrollPane(assetTable);
        add(scrollPane);
    }
}

最佳答案

不要使用null布局或使用setBounds()方法来定位和调整组件的大小。


但是我的imageBackground和按钮放错了地方


背景是容器组件。就是说,您将其创建为组件并将图像绘制为背景。然后,将其他组件添加到后台组件。现在,图像将显示在背景中,而其他组件则显示在其顶部。

请参见Background Panel给出创建背景组件的示例。

07-24 19:25