Java 按钮设置为左对齐,但仍显示为居中
我正在尝试用Swing创建一个接口 这是我的代码:Java 按钮设置为左对齐,但仍显示为居中,java,swing,Java,Swing,我正在尝试用Swing创建一个接口 这是我的代码: public class JavaApplication30 { public static void main(String[] args) throws IOException { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getConte
public class JavaApplication30
{
public static void main(String[] args) throws IOException
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS));
frame.setPreferredSize(new Dimension(1280, 720));
frame.setResizable(false);
frame.setContentPane(new JPanel()
{
BufferedImage image = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication29\\src\\eila.jpg"));
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, 1280, 720, this);
}
});
JPanel a = new JPanel();
a.setAlignmentX(Component.LEFT_ALIGNMENT);
a.setPreferredSize(new Dimension(150, 500));
a.setMaximumSize(new Dimension(150, 500));
a.setOpaque(false);
a.add(Box.createRigidArea(new Dimension(5,50)));
JButton amico = new JButton("Amico");
a.add(amico);
a.add(Box.createRigidArea(new Dimension(5,20)));
amico.setPreferredSize(new Dimension(150, 50));
JButton bello = new JButton("Bello");
a.add(bello);
a.add(Box.createRigidArea(new Dimension(5,20)));
bello.setPreferredSize(new Dimension(150, 50));
JButton compagno = new JButton("Compagno");
a.add(compagno);
compagno.setPreferredSize(new Dimension(150, 50));
frame.getContentPane().add(a);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
我将按钮对齐设置为左侧,但我的按钮仍然居中
如果没有背景的paintComponent,就不会发生这种情况
为什么会这样?如何对齐左侧的按钮
我将对齐设置为左侧,但我的按钮居中
setAlignmentX(…)只是提示如何在其父面板中对齐“面板”。将按钮添加到面板时,重要的是面板的布局管理器
默认情况下,JPanel使用FlowLayout
。默认情况下,创建流程布局时,添加到面板中的组件在面板空间中居中对齐
将布局管理器更改为组件左对齐的流程布局。阅读FlowLayout
API以获得正确的构造函数
此外,您可以在按钮之间提供默认间距,因此不需要Box.createRigidArea(…)。当您使用BoxLayout
时,该组件实际上是要使用的,您所说的很有效,但我对背景图像也有同样的问题,您能告诉我一种设置方法吗。