Java Jframe将我的按钮居中):<;
这是我的密码:Java Jframe将我的按钮居中):<;,java,swing,button,jframe,grid-layout,Java,Swing,Button,Jframe,Grid Layout,这是我的密码: public class Main { public static void main(String[] args){ JFrame frame = new JFrame("Vex Development Studio 2.0"); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(10,10); //make
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame("Vex Development Studio 2.0");
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(10,10);
//make variables
File newproject;
Container content = frame.getContentPane();
GridBagConstraints gbc = new GridBagConstraints ();
Dimension buttonsize = new Dimension(75,25);
Button about;
about = new Button("About");
about.setPreferredSize(buttonsize);
//add content
content.setLayout(new GridBagLayout());
content.setBackground(Color.white);
gbc.gridx = 0;
gbc.gridy = 0;
content.add(about,gbc);
//main stuff
//about button
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null, "Example", "About", 1);
}
});
//some extra crap
frame.setSize(700, 500);
frame.show();
//end
}
}
我有所有的代码,我有所有需要的导入,问题是:我需要按钮在窗口的左上角。提前谢谢!(:因为在gridbaglayout中,只有一个正方形 我建议用JButton代替Button
混合AWT和Swing是个坏主意。要将按钮定位到内容窗格的左上角,可以使用
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
或者等效于新的符号,我相信你可以使用
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
您必须允许按钮自行移动:
setLayout(null);
在创建按钮之前,请将其放在这里,这样您就可以自由移动按钮。以我的钱来说,我会避免使用GridBagLayout,而是使用nest JPanel,一个使用BorderLayout,另一个使用BoxLayout..show()方法不推荐使用,请使用.setVisible(true)代替。这是一个很好的按钮。+1