我正在尝试使用 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 中只有一个组件显示,为什么 以及如何显示所有组件
最佳答案
只需将文本字段添加到默认 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
中两次。您可能想要删除其中之一。
关于java - 尝试使用 gridBagLayout 在 JTable 上显示 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21193781/