import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class test
{
public static void main(String[] args)
{
CutterFrame frame = new CutterFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//窗口类
class CutterFrame extends JFrame
{
public static final int DEFAULT_WIDTH = 500;
public static final int DEFAULT_HEIGHT = 550;
public CutterFrame()
{
// get screen dimensions(获取屏幕尺寸)
Toolkit kit = Toolkit.getDefaultToolkit();//默认工具包
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setBounds(screenWidth/4,screenHeight/8,DEFAULT_WIDTH ,DEFAULT_HEIGHT);
setTitle("Super File Cutter");
setResizable(false);//不可改变窗口大小
CutPanel ctp = new CutPanel();
add(ctp);
}
}
//JPane
class CutPanel extends JPanel
{
private JLabel fn = new JLabel("File Name:");
private JTextField fntf = new JTextField(20);
private JButton b = new JButton("...");
private JLabel fs = new JLabel("File Size:");
private JTextField fstf = new JTextField(20);
public CutPanel()
{
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 4;
gbc.gridheight = 1;
add(fn,gbc);
gbc.gridx = GridBagConstraints.RELATIVE;
add(fntf,gbc);
add(b,gbc);
gbc.gridx = 0;
gbc.gridy++;
add(fs,gbc);
gbc.gridx = GridBagConstraints.RELATIVE;
add(fstf,gbc);
}
}
刚看了下GridBagLayout,然后编了一个简单的布局,但是程序运行后,CutPanel中的组件都会被放到面板中间,可是我gridx和gridy的值初始是0啊,不是应该放在面板左上角么??谢谢指导
------解决方案--------------------
- Java code
public CutPanel() { GridBagLayout layout = new GridBagLayout(); setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 4; gbc.gridheight = 1; add(fn, gbc); gbc.gridx = GridBagConstraints.RELATIVE; add(fntf, gbc); add(b, gbc); gbc.weighty = 1; gbc.gridx = 0; gbc.gridy++; add(fs, gbc); gbc.gridx = GridBagConstraints.RELATIVE; add(fstf, gbc); }