JTable 工作过程如下:
当一个表格显示之前,JTable 会询问每个单元格,getCellRender().getTableCellRendererComponent() 得到一个 Swing 组件后,就用它来在指定单元格显示出来。
当某个单元格即将获得焦点,比如单击或键盘tab 移动,JTable 会询问是否目标单元格允许编辑,如果允许就会询问 getCellEditor().getTableCellEditorComponent() 得到一个编辑器,通常,默认的编辑器是一个 JTextField 类型的,只要我们给一个 JButton 类型的就可以了。
table.setCellEditor(new TableCellEditor() {
private JButton editor = new JButton()
private JTextField dephaut = new JTextField()
{//相当于构造函数。
editor.addActionListener() {
/* 业务方法 */
}
}
/* 此处省略 N 多待实现方法*/
public Component getTableCellEditorComponent(
JTable table,
Object value,
boolean isSelected,
int row,
int column) {
if (column == 3) {
return this.editor
} else {
return this.dephaut
}
}
JButton有个构造函数是JButton(Icon icon),就是用来创建带图标的按钮的。可以这样用,如:
JButton jb = new JButton(new ImageIcon("images/myImage.gif"))
这样得到的就是带图标的按钮了。
import java.awt.BorderLayoutimport java.awt.EventQueue
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.border.EmptyBorder
import javax.swing.JButton
import java.awt.event.ActionListener
import java.awt.event.ActionEvent
import javax.swing.JTextField
import javax.swing.JLabel
public class FrameTest extends JFrame {
private JPanel contentPane
private JTextField textField
private JLabel lblNewLabel
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest()
frame.setVisible(true)
} catch (Exception e) {
e.printStackTrace()
}
}
})
}
/**
* Create the frame.
*/
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setBounds(100, 100, 450, 300)
contentPane = new JPanel()
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5))
setContentPane(contentPane)
contentPane.setLayout(null)
JButton btnNewButton = new JButton("确认")
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String string = textField.getText()
if(!string.equals("")){
lblNewLabel.setText(string)
contentPane.remove(textField)
contentPane. remove(btnNewButton)
contentPane.updateUI()
}
}
})
btnNewButton.setBounds(60, 10, 297, 50)
contentPane.add(btnNewButton)
textField = new JTextField()
textField.setBounds(60, 70, 297, 85)
contentPane.add(textField)
textField.setColumns(10)
lblNewLabel= new JLabel("")
lblNewLabel.setBounds(60, 165, 297, 56)
contentPane.add(lblNewLabel)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)