gpt4 book ai didi

java - 将 JButton 添加到 JTable

转载 作者:行者123 更新时间:2023-11-29 03:39:40 24 4
gpt4 key购买 nike

在 swing 中,是否可以在表格的标题上添加一个按钮。需要实现上述帖子的 Swing 。提前致谢。

最佳答案

是的,这是可能的。您只需将按钮添加到表格标题即可。唯一要知道的是 JTableHeader 没有布局,所以你需要设置一个。

这是一个简单的演示代码:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class TestTable2 {

protected void initUI() {
DefaultTableModel model = new DefaultTableModel();
for (int i = 0; i < 5; i++) {
model.addColumn("Col-" + (i + 1));
}
for (int i = 0; i < 200; i++) {
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < 5; j++) {
row.add("New cell - " + (j + 1));
}
model.addRow(row);
}
JTable table = new JTable(model);
final JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(button, "You have clicked me");
}
});
JTableHeader header = table.getTableHeader();
header.setLayout(new FlowLayout(FlowLayout.TRAILING, 5, 0));
header.add(button);
JFrame frame = new JFrame(TestTable2.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new TestTable2().initUI();
}
});
}

}

关于java - 将 JButton 添加到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13761260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com