0

見栄えが悪いので、Gridlayoutを使用せずにボタンと画像を整理したいと思います。

これは私が現在持っているものです:

ここに画像の説明を入力

これは私がそれをどのように見せたいかです:

ここに画像の説明を入力

パネルのコードは次のとおりです。アイデアはありますか?:

package hi.low;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Card_panel extends JPanel implements ActionListener
{
   private final int WIDTH = 400, HEIGHT = 200;

   private static String[] imageList =  { 
                                            "images/ac.png"
                                        };
   private static int imageNum = -1;

   JButton higher;
   JButton lower;

   public Card_panel()
   {

        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground (Color.green.darker().darker());

        ImageIcon image = new ImageIcon(imageList[0]);
        JLabel label = new JLabel("", image, JLabel.CENTER);
        add( label, BorderLayout.CENTER );

        JButton higher = new JButton("Higher");
        higher.setActionCommand("higher");
        higher.addActionListener (this);
        add( higher, BorderLayout.SOUTH );

        JButton lower = new JButton("Lower");
        lower.setActionCommand("lower");
        lower.addActionListener (this);
        add( lower, BorderLayout.SOUTH );


   }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String Action;
        Action = e.getActionCommand ();

        if (Action.equals ("higher"))
        {
            System.out.println("User chose higher!");
        }

        if (Action.equals ("lower"))
        {
            System.out.println("User chose lower!");
        }

    }

}

ありがとうございました!

4

1 に答える 1

1

JPanelデフォルトでは を使用してFlowLayoutいますが、変更しているという証拠が見られないため、パネルが使用しているレイアウトだと思います...

代わりに、GridBagLayout...

public Card_panel()
{

    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setBackground (Color.green.darker().darker());

    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2;

    ImageIcon image = new ImageIcon(imageList[0]);
    JLabel label = new JLabel("", image, JLabel.CENTER);
    add( label, gbc );

    gbc.gridx = 0;
    gbc.gridy++;
    gbc.gridwidth = 1;
    JButton higher = new JButton("Higher");
    higher.setActionCommand("higher");
    higher.addActionListener (this);
    add( higher, gbc );

    gbc.gridx++;
    JButton lower = new JButton("Lower");
    lower.setActionCommand("lower");
    lower.addActionListener (this);
    add( lower, gbc );


}

複合レイアウトを使用して、ボタンを独自のレイアウトで独自のパネルに配置し、別のレイアウトを使用してラベルとボタン ペインをレイアウトすることもできます。

于 2013-06-06T05:09:04.337 に答える