Swing アプリケーションを作成しています。移動体アプリの一種のロードマップです。形状コンポーネントを 2 つJPanel
の に分割します。1 つは static component JPanel
、2 つ目は dynamic componentJPanel
で、両方とも mainPanel に追加されています。両方のパネルが重なっており、動的コンポーネント パネルの場合、opaque を false にして透明にします。動的コンポーネント パネルの再描画を行うと、静的コンポーネント パネルの再描画もトリガーされます。動的コンポーネント パネルの形状に変更があり、静的コンポーネント パネルの形状が消去されるべきでない場合、毎回静的コンポーネント パネルを再描画したくありません。
現在、私のロジックは以下のとおりです。疑似コードです。静的コンポーネントの上に可動コンポーネントを描画し、起動時に静的コンポーネントを一度描画する方法を教えてください。
public class layeredpanel extends JFrame
{
private JPanel contentPane;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
layeredpanel frame = new layeredpanel();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public layeredpanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout( new OverlayLayout(panel) );
final JPanel layer_1 = new layer1();
layer_1.setOpaque(false);
panel.add(layer_1);
JPanel layer_2 = new layer2();
panel.add(layer_2);
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
while(true)
{try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
layer_1.repaint();
}
}
});
thread.start();
}
class layer1 extends JPanel
{
@Override
public void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
System.out.println("Paint1");
g.setColor(Color.blue);
g.drawRect(30, 20, 40, 40);
}
}
class layer2 extends JPanel
{
@Override
public void paintComponent(Graphics g)
{
System.out.println("Paint2");
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(30, 20, 20, 20);}
}
}
出力:ペイント2
Paint1
Paint2
Paint1
Paint2
Paint1
Paint2
Paint1
Paint2
Paint1
Paint2
Paint1
Paint2
Paint1