> Почему метод Paint() рисует фон поверх кнопки?
Унаследовали свой класс от JFrame - вот и получили что просили.
https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html > и как это исправить?
Исправить что?
public class Q232320240 implements Runnable {
private static final String FRAME_TITLE = "232320240";
private JFrame frame;
private BackgroundPaint background;
private Timer timer;
@Override
public void run() {
initComponents();
initEvents();
frame.pack();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
this.timer = new Timer(2500, this::render);
timer.start();
}
private void initComponents() {
frame = new JFrame(FRAME_TITLE);
JButton button = new JButton("Button");
button.setBounds(40, 30, 200, 50);
background = new BackgroundPaint();
background.setPreferredSize(new Dimension(500, 500));
background.setBounds(0, 0, 500, 500);
JLayeredPane lp = frame.getLayeredPane();
lp.setLayout(null);
lp.add(background, JLayeredPane.DEFAULT_LAYER);
lp.add(button, Integer.valueOf(JLayeredPane.DEFAULT_LAYER + 2));
}
private void initEvents() {
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (timer != null) {
timer.stop();
}
frame.setVisible(false);
frame.dispose();
}
});
}
private void render(ActionEvent actionEvent) {
RepaintManager rm = RepaintManager.currentManager(frame);
rm.addDirtyRegion(background, 0, 0, 500, 500);
rm.paintDirtyRegions();
}
public static void main(String[] args) {
try {
SwingUtilities.invokeLater(new Q232320240());
} finally {
System.out.println("Main thread is terminated");
}
}
private static class BackgroundPaint extends JComponent {
BackgroundPaint() {
super();
setOpaque(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g1 = g.create();
g1.setColor(Color.black);
g1.fillRect(0,0,500, 500);
g1.setColor(Color.RED);
g1.drawString("" + System.currentTimeMillis() + " ", 100, 100);
g1.dispose();
}
}
}