gpt4 book ai didi

java - JPanel 在没有 GridLayout 的情况下组织按钮/图像/等

转载 作者:行者123 更新时间:2023-12-01 14:29:14 26 4
gpt4 key购买 nike

所以我想在不使用 Gridlayout 的情况下组织我的按钮和图像,因为它看起来很糟糕。

这是我目前拥有的:

enter image description here

这就是我想要的样子:

enter image description here

这是面板的代码,有什么想法吗?:

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!");
}

}

}

谢谢!

最佳答案

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 );


}

您还可以使用复合布局,将按钮放置在自己的面板中,使用自己的布局,然后使用不同的布局来布局标签和按钮 Pane

关于java - JPanel 在没有 GridLayout 的情况下组织按钮/图像/等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com