我有这个代码加载5个图像并使用FlowLayout将它们放入框架中:
public class Main
{
private static final int verticalGap=50;
private static final int horizontalGap=30;
private static final int width= 800;
private static final int height= 800;
public static void main(String[] args)
{
FlowLayout layout=new FlowLayout(FlowLayout.LEADING,horizontalGap,verticalGap);
JButton button= new JButton("Discard");
ImagePanel[] panels= new ImagePanel[5];
Deck deck= new Deck();
JFrame frame= new JFrame("Poker");
frame.setSize(width, height);
frame.setLayout(layout);
frame.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
deck.mix();
for(int i=0; i<5; i++)
{
panels[i]= new ImagePanel();
panels[i].setImage(deck.getCard(i));
frame.getContentPane().add(panels[i]);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
代码加载5张卡并正确找到它们
但问题是,现在我想在框架上放置一个按钮。这个按钮应该大约放在屏幕的中央,但如果我将它添加到窗格,按钮就会放在其他面板附近,使用水平流量布局设定的差距。
如何在不改变面板位置的情况下将其放置在绝对位置(因此我希望使用流程布局添加5个面板,并在绝对位置添加一个按钮)。
答案 0 :(得分:3)
您不能将绝对布局与LayoutManager混合使用。
在这种情况下:
这是与该解决方案对应的代码(但我无法测试它,因为我没有其他类)。
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main {
private static final int verticalGap = 50;
private static final int horizontalGap = 30;
private static final int width = 800;
private static final int height = 800;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main().initUI();
}
});
}
private void initUI() {
FlowLayout layout = new FlowLayout(FlowLayout.LEADING, horizontalGap, verticalGap);
JButton button = new JButton("Discard");
ImagePanel[] panels = new ImagePanel[5];
Deck deck = new Deck();
JFrame frame = new JFrame("Poker");
frame.setSize(width, height);
frame.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
deck.mix();
JPanel deckPanel = new JPanel(layout);
for (int i = 0; i < 5; i++) {
panels[i] = new ImagePanel();
panels[i].setImage(deck.getCard(i));
deckPanel.add(panels[i]);
}
frame.getContentPane().add(deckPanel);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(button);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();// Sets the frame size to its preferred size.
// You can also call setSize() instead
frame.setVisible(true);
}
}