O código a seguir desenha uma linha na JTable, e ao clicar no botão mostra a caixa de diálogo.
O problema é que a caixa de diálogo apaga a linha desenhada na tabela…
package jTable;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
public class Table extends JTable {
private static final long serialVersionUID = 1L;
//Singleton
private static Table tableInstance = new Table(10,2);
public static Table getInstance() {return tableInstance;}
private Table(int row, int col) {
super(row,col);
}
//Desenha a linha na tabela
public static void drawLine(){
Graphics g = tableInstance.getGraphics();
g.drawLine(0, 0, 200, 500);
}
@Override
public void repaint(){
super.repaint();
if(tableInstance != null)
drawLine();
}
//Cria jFrame
private static JFrame jFrame;
public static JFrame getJFrame() {
if( jFrame == null ) {
jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(new Dimension(300,300));
jFrame.setLocationRelativeTo(null); //center
jFrame.setVisible(true);
}
return jFrame;
}
public static void main(String[] args) {
JFrame frame = getJFrame();
Table tab = Table.getInstance();
JButton btn = new JButton("Show dialog");
//Configura o JButton para mostrar a caixa de diálogo
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
drawLine();
tableInstance.add(new JLabel("TEST"));
JOptionPane.showInputDialog("Dialog box");
}
});
frame.getContentPane().add(tab, BorderLayout.NORTH);
frame.add(btn, BorderLayout.SOUTH);
}
}
Qual o listener para “Ao apagar o desenho” ou “Ao arrastar uma janela por cima” eu chamar novamente o drawLine() ?