📄 gridbagdemo2.java
字号:
// Demonstrating GridBagLayout constants.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GridBagDemo2 extends JFrame {
private GridBagLayout gbLayout;
private GridBagConstraints gbConstraints;
private Container container;
public GridBagDemo2()
{
super( "GridBagLayout" );
container = getContentPane();
gbLayout = new GridBagLayout();
container.setLayout( gbLayout );
// instantiate gridbag constraints
gbConstraints = new GridBagConstraints();
// create GUI components
String metals[] = { "Copper", "Aluminum", "Silver" };
JComboBox comboBox = new JComboBox( metals );
JTextField textField = new JTextField( "TextField" );
String fonts[] = { "Serif", "Monospaced" };
JList list = new JList( fonts );
String names[] =
{ "zero", "one", "two", "three", "four" };
JButton buttons[] = new JButton[ names.length ];
for ( int i = 0; i < buttons.length; i++ )
buttons[ i ] = new JButton( names[ i ] );
// define GUI component constraints
// textField
gbConstraints.weightx = 1;
gbConstraints.weighty = 1;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( textField );
// buttons[0] -- weightx and weighty are 1: fill is BOTH
gbConstraints.gridwidth = 1;
addComponent( buttons[ 0 ] );
// buttons[1] -- weightx and weighty are 1: fill is BOTH
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
addComponent( buttons[ 1 ] );
// buttons[2] -- weightx and weighty are 1: fill is BOTH
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( buttons[ 2 ] );
// comboBox -- weightx is 1: fill is BOTH
gbConstraints.weighty = 0;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( comboBox );
// buttons[3] -- weightx is 1: fill is BOTH
gbConstraints.weighty = 1;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( buttons[ 3 ] );
// buttons[4] -- weightx and weighty are 1: fill is BOTH
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
addComponent( buttons[ 4 ] );
// list -- weightx and weighty are 1: fill is BOTH
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( list );
setSize( 300, 200 );
show();
}
// addComponent is programmer-defined
private void addComponent( Component c )
{
gbLayout.setConstraints( c, gbConstraints );
container.add( c ); // add component
}
public static void main( String args[] )
{
GridBagDemo2 app = new GridBagDemo2();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -