在一个JText区域中显示多个选中行的值,可以通过以下步骤实现:
以下是一个示例代码,演示如何在JText区域中显示多个选中行的值:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SelectedRowsDemo extends JFrame {
private JTable table;
private JTextArea textArea;
public SelectedRowsDemo() {
setTitle("Selected Rows Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 创建一个表格
String[] columnNames = {"ID", "Name", "Age"};
Object[][] data = {
{1, "Alice", 25},
{2, "Bob", 30},
{3, "Charlie", 35},
{4, "David", 40}
};
table = new JTable(data, columnNames);
// 创建一个显示选中行的JText区域
textArea = new JTextArea();
textArea.setEditable(false);
// 创建一个按钮,点击时显示选中行的值
JButton button = new JButton("Show Selected Rows");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取选中行的索引
int[] selectedRows = table.getSelectedRows();
// 构建显示字符串
StringBuilder sb = new StringBuilder();
for (int row : selectedRows) {
for (int col = 0; col < table.getColumnCount(); col++) {
sb.append(table.getValueAt(row, col)).append("\t");
}
sb.append("\n");
}
// 设置JText区域的文本
textArea.setText(sb.toString());
}
});
// 将表格和按钮添加到窗口中
add(new JScrollPane(table), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
add(new JScrollPane(textArea), BorderLayout.EAST);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SelectedRowsDemo().setVisible(true);
}
});
}
}
在这个示例中,我们创建了一个包含表格、按钮和JText区域的窗口。当用户点击按钮时,程序会获取选中行的值,并将其显示在JText区域中。
这个示例中没有涉及到腾讯云的相关产品,因此无需提供相关链接。
领取专属 10元无门槛券
手把手带您无忧上云