今日、さまざまな質問をサーフィンしているときに、1つの質問に遭遇しました。これは少し奇妙に思えますが、なぜにを追加したいのでしょうかJPanel
。JLabel
そのような状況が発生する可能性があるという本当の理由があるので、それは些細なことですか。
3 に答える
はい、JLabelにコンポーネントを追加したい本当の理由があります。JLabelでImageIconを設定および交換するのは簡単なので、GUIのバッキングイメージとして使用することも珍しくありません。
編集
あなたの状態:
ああ、つまり、コンテナに特定の背景を持たせたい場合は、そのようなものが存在できるプラットフォームとしてJLabelを使用する必要がありますか?私は正しいですか?
いいえ、必要に応じてJPanelで背景画像を描画するのはかなり簡単なので、これにJLabelを使用する必要はありません。そのpaintComponent(...)
方法で画像を描くだけです。
GUIのBGとしてのアニメーション画像。Icon
HTML を使用してこのサイズを変更します (x3) が、既に目的のサイズになっている場合は、ラベルの として直接設定できます。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class LabelAsBackground {
public static final String HTML =
"<html>" +
"<style type'text/css'>" +
"body, html { padding: 0px; margin: 0px; }" +
"</style>" +
"<body>" +
"<img src='http://pscode.org/media/starzoom-thumb.gif'" +
" width=320 height=240>" +
"";
LabelAsBackground() {
JFrame f = new JFrame("Animated Image BG");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel contentPane = new JLabel(HTML);
contentPane.setLayout(new GridLayout());
JPanel gui = new JPanel(new GridLayout(3,3,15,15));
gui.setOpaque(false);
contentPane.add(gui);
gui.setBorder(new EmptyBorder(20,20,20,20));
for (int ii=1; ii<10; ii++) {
gui.add( new JButton("" + ii));
}
f.setContentPane(contentPane);
f.pack();
//f.setResizable(false); // uncomment to see strange effect..
f.setVisible(true);
}
public static void main(String[] args) {
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
LabelAsBackground lab = new LabelAsBackground();
}
});
}
}
それが「本物」かどうかはわかりません。これは、多くの説明が必要な主観的な用語のようです。私はこの方法を使用したことがなく、今夜手探りでそれを理解しただけです。;)
this seems to me a bit weird, why would one wants to add
a JPanel to a JLabel,
はい、そうです
are there any genuine reasons as to such situation can arise,
so is it just trivial?
いいえ、簡単ではありません。 // と pre_implemented しかないため、JFrame
残りJDialog
の" " については、プログラムで適切な LayoutManager を宣言する必要がありますJWindow
JPanel
LayoutManager
Custom JComponent