I'm using a single row JTabel with a MouseAdapter attached to it. The table model is populated with some random values. Upon right-clicking the table a JPopupMenu with several JMenuItems will appear. Visual artifacts start showing if part of the popup was drawn outside of the panel it's attached to at some point. Interestingly enough this only seems to happen if the popup doesn't have many items attached to it. Any popup with more than seven items has been working consistently for me.
Only tested on Windows 10 64 bit with Java 1.8.0_112-b15.
Why does this happen and is there a workaround?
public class PopupTest {
private static final int NUM_POPUP_ITEMS = 3;
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private TableModel model = new TableModel();
private JTable table = new JTable();
public static void main(String[] a) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PopupTest();
}
});
}
public PopupTest() {
panel.setLayout(new BorderLayout());
panel.add(table, BorderLayout.CENTER);
panel.setPreferredSize(new Dimension(400, 500));
table.setModel(model);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent event) {
popup(event);
}
});
frame.setLocation(150, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
private void popup(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
JPopupMenu menu = new JPopupMenu();
for (int i = 0; i < NUM_POPUP_ITEMS; i++) {
menu.add(new JMenuItem(String.valueOf(i)));
}
menu.show(panel, e.getX(), e.getY());
}
}
private class TableModel extends AbstractTableModel {
private List<Double> dataList = new ArrayList<>();
public TableModel() {
for (int i = 0; i < 40; i++) {
dataList.add(Math.random());
}
}
@Override
public int getRowCount() {
return dataList.size();
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return dataList.get(rowIndex);
}
}
}
-Dsun.java2d.d3d=false
or-Dsun.java2d.opengl=true
, may help. – Interminable