java
1import javax.swing.*; 2import java.awt.*; 3import java.awt.event.ActionListener; 4import java.awt.event.MouseAdapter; 5 6public class TestMain extends JFrame { 7 8 private static final Dimension frameSize = new Dimension(400,600); 9 private final JPanel mainPanel; 10 public static void main(String[] args) { 11 new TestMain(); 12 } 13 14 public TestMain() { 15 this.mainPanel = getPanel(); 16 getContentPane().add(mainPanel); 17 setDefaultCloseOperation(EXIT_ON_CLOSE); 18 setPreferredSize(frameSize); 19 setSize(frameSize); 20 setVisible(true); 21 } 22 23 private JPanel getPanel() { 24 JPanel basePanel = new JPanel(); 25 basePanel.setLayout(new OverlayLayout(basePanel)); 26 basePanel.setPreferredSize(frameSize); 27 28 SpringLayout layout = new SpringLayout(); 29 JPanel panel1 = new JPanel(layout); 30 panel1.setPreferredSize(frameSize); 31 32 JButton button1 = new JButton(); 33 button1.setText("button1"); 34 button1.addActionListener(getListener()); 35 layout.putConstraint(SpringLayout.VERTICAL_CENTER,button1,0,SpringLayout.VERTICAL_CENTER,panel1); 36 layout.putConstraint(SpringLayout.HORIZONTAL_CENTER,button1,0,SpringLayout.HORIZONTAL_CENTER,panel1); 37 panel1.add(button1); 38 39 basePanel.add(panel1); 40 41 42 return basePanel; 43 } 44 private ActionListener getListener() { 45 SpringLayout layout2 = new SpringLayout(); 46 JPanel backGround = new JPanel(layout2); 47 //---------backGround------------------ 48 backGround.setPreferredSize(frameSize); 49 backGround.setBackground(new Color(0,0,0,150)); 50 MouseAdapter adapter = new MouseAdapter() { 51 }; 52 backGround.addMouseMotionListener(adapter); 53 backGround.addMouseListener(adapter); 54 //------------------------------------- 55 SpringLayout layout = new SpringLayout(); 56 JPanel panel = new JPanel(layout); 57 panel.setPreferredSize(new Dimension(400,50)); 58 59 JButton button2 = new JButton(); 60 button2.setText("button2"); 61 layout.putConstraint(SpringLayout.VERTICAL_CENTER,button2,0,SpringLayout.VERTICAL_CENTER,panel); 62 layout.putConstraint(SpringLayout.HORIZONTAL_CENTER,button2,0,SpringLayout.HORIZONTAL_CENTER,panel); 63 panel.add(button2); 64 65 layout2.putConstraint(SpringLayout.NORTH,panel,40,SpringLayout.NORTH,backGround); 66 backGround.add(panel); 67 68 return event -> { 69 mainPanel.add(backGround); 70 mainPanel.setComponentZOrder(backGround,0); 71 mainPanel.validate(); 72 mainPanel.repaint(); 73 }; 74 } 75}
上記のコードで実行したところbutton2
を押したときにbutton1
がbackGround
を貫通して最前面に表示されてしまいます。
```backGround.getComponentZOrder()``に変化はありませんでした。
どう改善すればよいかご教授いただきたいです。
回答1件
あなたの回答
tips
プレビュー