5

背景画像があるJFrameと、いくつかのコマンドを実行する画像JButtonsを修正しようとしています。JFrameの特定の場所に小さなボタンを配置したいので、レイアウトなしでやろうとしましたが、毎回背景画像が前面に来るか、JFrameのサイズがJFrameのサイズと同じです。次のコードでは、JButton は JFrame と同じサイズになります。JButton のサイズと位置を変更しようとしましたが、何もしませんでした。助けてください。

ここにコードがあります


public final class Test extends JComponent
{
 private Image background;
 private JFrame frame;
 private Dimension dimension;

public Test()
{  
    dimension = new Dimension(15, 15);
    frame = new JFrame("Iphone");
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(this);
    frame.setBounds(641, 0, 344, 655);
    frame.setVisible(true);

    test = displayButton("tigka");
    frame.getContentPane().add(test);
}

public void update(Graphics g)
{
    paint(g);
}


public void paintComponent(Graphics g)
{
    super.paintComponents(g);
    g.drawImage(background, 0, 25, null); // draw background

// label();

test = displayButton("test"); } public JButton displayButton(String name) { JButton button = new JButton(name); button.setSize(100, 100); button.setPreferredSize(dimension); return button; }

4

4 に答える 4

6

content paneの背景を取得するには、を変更する必要がありますFrame

public static void main(String[] args) throws IOException {

    JFrame frame = new JFrame("Test");

    frame.setContentPane(new JPanel() {
        BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, 300, 300, this);
        }
    });

    frame.add(new JButton("Test Button"));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);
}

出力:

スクリーンショット

于 2011-05-06T14:46:16.737 に答える
1

ラベルに HTML を含む JLabel を使用してみましたか? このようなもの:

import javax.swing.*;

public class SwingImage1
{
  public static void main( String args[] )
  {
    JFrame  frm = new JFrame( "Swing Image 1" );
    JLabel  lbl = new JLabel( "<html><body><img src=\"http://liv.liviutudor.com/images/liv.gif\"></body></html>" );
    frm.getContentPane().add( lbl );
    frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frm.pack();
    frm.setVisible( true );
  }
}

次に、ラベルの上にボタンを追加できますか?

于 2011-05-06T14:38:33.367 に答える
1

これらの 2 行を交換する必要があります。

super.paintComponents(g);  //paints the children, like the button
g.drawImage(background, 0, 25, null); // draw background later possibly overwriting the button

したがって、次の順序にする必要があります。

g.drawImage(background, 0, 25, null);
super.paintComponents(g); 

さらに、コンテンツ ペインのデフォルト レイアウトは BorderLayout であることに注意してください。したがって、コンテンツ ペインのレイアウトを明示的に null に設定します。

于 2011-05-06T14:39:52.227 に答える