当前位置: 代码迷 >> J2SE >> 请教下关于按钮的位置
  详细解决方案

请教下关于按钮的位置

热度:190   发布时间:2016-04-24 17:21:08.0
请问下关于按钮的位置
这是《core   java》里面的一个按钮测试的程序

import   java.awt.*;
import   java.awt.event.*;
import   javax.swing.*;
public   class   ButtonTest   {

public   static   void   main(String[]   agrs)
{
ButtonFrame   frame   =   new   ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}

}
class   ButtonFrame   extends   JFrame
{
          public   ButtonFrame()
          {
          setTitle( "ButtonTest ");
          setSize(300,   200);
         
          ButtonPanel   panel   =   new   ButtonPanel();
          Container   contentPane   =   getContentPane();
          contentPane.add(panel);
          }


}
class   ButtonPanel   extends   JPanel
{
public   ButtonPanel()
{

JButton   yellowButton   =   new   JButton( "Yellow ");
JButton   blueButton   =   new   JButton( "Blue ");
JButton   redButton   =   new   JButton( "Red ");

add(yellowButton);
        add(redButton);
add(blueButton);

ColorAction   yellowAction   =   new   ColorAction(Color.YELLOW);
ColorAction   blueAction     =   new   ColorAction(Color.BLUE);
ColorAction   redAction   =   new   ColorAction(Color.RED);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);

}

private   class   ColorAction   implements   ActionListener
{
public   ColorAction(Color   c)
{
backgroundColor   =   c;
}
public   void   actionPerformed(ActionEvent   event)
{
setBackground(backgroundColor);
}

private   Color   backgroundColor;
}
}

请问下按钮的位置可不可以自定义的啊?
谢谢!

------解决方案--------------------
Panel的布局方式默认是FlowLayout(没记错的话),就是说加上去的按钮是挨个往上放的,位置自己不能设定,要想自己设置位置,那么这样改
class ButtonPanel extends JPanel
{
public ButtonPanel()
{
this.setLayout(null);
JButton yellowButton = new JButton( "Yellow ");
JButton blueButton = new JButton( "Blue ");
JButton redButton = new JButton( "Red ");


yellowButton.setBounds(左上角坐标X,左上角坐标Y,按钮宽度,按钮高度);
redButton.setBounds(左上角坐标X,左上角坐标Y,按钮宽度,按钮高度);
blueButton.setBounds(左上角坐标X,左上角坐标Y,按钮宽度,按钮高度);

add(yellowButton);
add(redButton);
add(blueButton);

ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);

}

private class ColorAction implements ActionListener
{
public ColorAction(Color c)
  相关解决方案