我正在用 Java 制作一个聊天应用程序。他们可以添加 friend 并与他们聊天。
这是我添加 friend JFrame
的想法:
我尝试用谷歌搜索Multi jpanel in one jscrollpane
但我什么也没找到。我最终得到了自定义 JTable
。我想创建一个自定义的JTable
,它在每个槽的不同位置都有JLabel
。用户只需在JTable
中选择一个槽位,然后就可以使用下面的JButton
与其聊天。
用Java可以实现这个功能吗?是的,请分享您的想法。谢谢。
最佳答案
这是一个提案。但它还存在一些缺陷
- 大小传播是固定的(可能是更好的基于客户端或服务器的大小调整)
- 没有事件委托(delegate)给底层
组件
- 性能,因为重量级面板实例是在绘制循环内频繁创建的
但这是如何做到的。代码被分成几个部分。
值类
只是一个简单的类来表示面板中每个单元格的日期。
class Value {
public final String text;
public final boolean flag;
public Value(String text, boolean flag) {
this.text = text;
this.flag = flag;
}
}
我的个人小组类(class)
可以在 GUI 编辑器(如 Google 的窗口生成器)中对表示进行建模。该面板利用该值并相应地显示它。
public class MyPanel extends JPanel {
public MyPanel(Value v) {
JLabel lblNewLabel = new JLabel(v.text);
add(lblNewLabel);
JCheckBox chckbxSomeValue = new JCheckBox("some value");
chckbxSomeValue.setSelected(v.flag);
add(chckbxSomeValue);
}
}
表格单元格渲染器类
仅返回一些显示所需值的面板实例。
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
class MyPanelCellRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return new MyPanel((Value)value); // maybe performance problem
}
}
自定义表格模型
import javax.swing.table.DefaultTableModel;
class MyTableModel extends DefaultTableModel {
public MyTableModel() {
super(new Object[][] {
new Object[] { 1, new Value("asdf", true) },
new Object[] { 2, new Value("qwer", false) } },
new String[] {"Id", "MyPanel" });
}
Class[] columnTypes = new Class[] { Integer.class, Value.class };
MyTableModel(Object[][] data, Object[] columnNames) {
super(data, columnNames);
}
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
}
框架类
import java.awt.BorderLayout;
public class MyFrame {
JFrame frame;
private JTable table;
public MyFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable();
table.setModel(new MyTableModel());
table.setFillsViewportHeight(true);
table.getColumnModel()
.getColumn(1)
.setCellRenderer(new MyPanelCellRenderer());
table.setRowHeight(40); // static sizing
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
}
}
主要功能
import java.awt.EventQueue;
public class MyApp {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame window = new MyFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
最终结果
面板 MyPanel
是使用 eclipse 和 google 的窗口生成器创建的
关于java - 如何创建自定义 JTable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228208/