问题
What I want to do is put the button down the bottom left of the application. Could somebody just give me an example of how to do it?
This is what I have:
Here's my code:
super("Test");
/**Create Components**/
JPanel addPanel = new JPanel();
JButton addButton= new JButton("Add");
/**Add Components**/
addPanel.add(addButton);
this.add(addPanel);
/**Set Components Properties**/
addButton.setLocation(12, 371);
addButton.setPreferredSize(new Dimension(116, 40));
addPanel.setLocation(12, 371);
addPanel.setPreferredSize(new Dimension(116, 40));
/**Frame Properties**/
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(dimension1, dimension2));
this.setResizable(false);
this.pack();
this.setVisible(true);
回答1:
Try BorderLayout
addPanel.setLayout(new BorderLayout());
addPanel.add(addButton,BorderLayout.SOUTH);
Even inside you addPanel you can have another panel(say bottomLeft) with Grid Layout
bottomLeft.setLayout(new GridLayout(1,3,200,0));
bottomLeft.add(addPanel)
回答2:
Firstly set the frame's layout to null
if you are using JFrame, or set layout's panel to null
if you are using panel,then use setBounds()
method :
button.setBounds(x,y,width,height);
See this example I made for you :
import javax.swing.*;
import java.awt.*;
public class ButtonLocationDemo extends JFrame{
private JButton button;
public ButtonLocationDemo(){
JPanel p = new JPanel();
button = new JButton("Button");
p.setLayout(null);
button.setBounds(40,100,100,60);
p.add(button);
getContentPane().add(p);
//setLayout(null);
setDefaultCloseOperation(3);
setSize(400,400);
setVisible(true);
}
public static void main(String...args){
new ButtonLocationDemo();
}
}
来源:https://stackoverflow.com/questions/16756903/how-to-set-the-location-of-a-button-anywhere-in-your-jframe