[英]How to align Button in a JPanel this way
我正在尝试使用JPanel
和JButton
创建图形界面。 到目前为止,这很好,但当我创建JButton
实例时,它们似乎在同一行内对齐。 我希望每个按钮都在同一行中,而不是全部都在同一行中。
如何达到理想的效果?
public class Interface extends JFrame{
public Interface ()
{
//frame
super("Panel");
pack();
setSize(500,400);
setVisible(true);
//declaration container
Container c;
c=getContentPane();
c.setLayout(new BorderLayout());
//declaration des panel avec leurs caracteristiques
JPanel menu =new JPanel();
JPanel MessageList =new JPanel();
JPanel about=new JPanel();
menu.setLayout(new FlowLayout());
MessageList.setLayout(new FlowLayout());
about.setLayout(new FlowLayout());
menu.setBackground(Color.blue);
MessageList.setBackground(Color.cyan);
about.setBackground(Color.cyan);
c.add(menu,BorderLayout.WEST);
c.add(MessageList,BorderLayout.EAST);
c.add(about,BorderLayout.SOUTH);
//--------Button---------------------
JButton button1=new JButton("button1");
JButton button2=new JButton("Button2");
menu.add(button1);
menu.add(button2);
//-----------------------------
}
public static void main(String args[])
{
Interface Message=new Interface();
Message.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
使用嵌套布局。 黄色和蓝色面板分别具有自己的布局,然后放置在较大布局的约束中。
import java.awt.*;
import javax.swing.*;
public class Interface extends JFrame{
public Interface ()
{
//frame
super("Panel");
//declaration container
Container c;
c=getContentPane();
c.setLayout(new BorderLayout());
c.setBackground(Color.white);
//declaration des panel avec leurs caracteristiques
JPanel menu =new JPanel(new GridLayout(0,1,3,3));
JPanel messageList =new JPanel(new FlowLayout());
JPanel about=new JPanel(new FlowLayout());
menu.setBackground(Color.blue);
messageList.setBackground(Color.cyan);
messageList.add(new JLabel("'messageList' padder"));
about.setBackground(Color.green);
about.add(new JLabel("'about' padder"));
JPanel menuConstrain = new JPanel(new BorderLayout());
menuConstrain.setBackground(Color.yellow);
menuConstrain.add(menu,BorderLayout.NORTH);
c.add(menuConstrain,BorderLayout.WEST);
c.add(messageList,BorderLayout.EAST);
c.add(about,BorderLayout.SOUTH);
//--------Button---------------------
JButton button1=new JButton("button1");
JButton button2=new JButton("Button2");
menu.add(button1);
menu.add(button2);
//-----------------------------
pack();
setSize(300,150);
setVisible(true);
}
public static void main(String args[])
{
Interface Message=new Interface();
Message.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
有关使用嵌套布局的更全面的示例,请参见NestedLayoutExample.java
。
顺便说一句-这是一些令人困惑的代码!
Interface
的具体类。 menu
的面板。 Panel
。 这是一个穷人的迷恋形式吗?
请注意,应在EDT上创建Swing GUI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.