尝试使用gridBagLayout在JTable上显示JTextField

时间:2014-01-17 19:01:47

标签: java swing gridbaglayout

我试图使用GridBagLayout将JTextFild放在JTable上,但事情只有一个组件正在显示。这意味着我必须为每个组件添加一个JPanel,因为我试图在JPanel上添加它们,然后我尝试将它们添加到容器中。

这段代码:

  package AnimeAid;

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


/**
 *
 * @author isslam
 */
public class GuiInterface extends JFrame {
    JTable table;
    JTextField enterText;
     public static void main(String[] args) {
     GuiInterface is = new GuiInterface("t");
     is.setVisible(true);
     }

    public GuiInterface(String title){
    setSize(900, 700);
    setTitle(title);
    setDefaultCloseOperation(GuiInterface.EXIT_ON_CLOSE);
    String[] columnNames = {"#","Start","End","Translation column"};
    Object[][] data = {
    {"1", "00:00:01,600","00:00:04,080", "Mr Magnussen, please state your\n" +
    "full name for the record."},
    {"2", "00:00:04,080 ","00:00:07,040","Charles Augustus Magnussen."}};
    enterText = new JTextField();

    table = new JTable(data, columnNames);
    table.setFillsViewportHeight(true);
    table.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
        TableColumn columnA = table.getColumn("#");
        columnA.setMinWidth(10);
        columnA.setMaxWidth(20);
        TableColumn columnB= table.getColumn("Start");
        columnB.setMinWidth(80);
        columnB.setMaxWidth(90);

        TableColumn columnC= table.getColumn("End");
        columnC.setMinWidth(80);
        columnC.setMaxWidth(90);

        JPanel textFiled = new JPanel(new GridBagLayout());
        textFiled.add(enterText);
        GridBagConstraints co = new GridBagConstraints();
        co.fill = GridBagConstraints.HORIZONTAL;
        co.gridx =0;
        co.gridy =0;
        co.weightx=0.5;
        co.weighty=1;
        co.gridheight=0;
        co.gridwidth=0;
        co.ipadx=900;
        co.ipady=80;
        co.anchor = GridBagConstraints.PAGE_START;
        co.insets = new Insets(5, 5, 0, 0);
        textFiled.add(enterText,co);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        Container cp = getContentPane();
        cp.add(textFiled);



    }}

它应该是什么样子但发生了什么只是一个组件在JFrame中显示为什么 以及如何显示所有组件

example

1 个答案:

答案 0 :(得分:2)

只需将文本字段添加到默认BorderLaoyout的NORTH位置即可。而不是这个

    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane);

    Container cp = getContentPane();
    cp.add(textFiled);

就这样做

    JScrollPane scrollPane = new JScrollPane(table);
    add(scrollPane, BorderLayout.CENTER);

    add(textFiled, BordderLayout.NORTH);

另外,为什么您要将enterText两次添加到textFiled。您可能想要删除其中一个。