Java-GUI

Posted SunCY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java-GUI相关的知识,希望对你有一定的参考价值。

首先是这么一个框架

包含了类怎么写,怎么初始化,怎么设置布局,放置按钮,按钮怎么添加监听器

package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest extends JFrame {
   private JButton plainButton, fancyButton;
   // set up GUI
   public ButtonTest()
   {  super( "JButton的程序设计" );

      // get content pane and set its layout
      Container container = getContentPane();
      container.setLayout( new FlowLayout() );

      // create buttons
      plainButton = new JButton( "文本按钮" );
      container.add( plainButton ); 
      // create an instance of inner class ButtonHandler
      // to use for button event handling 
      ButtonHandler handler = new ButtonHandler(); 
      plainButton.addActionListener( handler );

      setSize( 275, 100 );
      setVisible( true );

   } // end ButtonTest constructor

   public static void main( String args[] )
   { 
      ButtonTest application = new ButtonTest();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

   // inner class for button event handling
   private class ButtonHandler implements ActionListener { 
      // handle button event
      public void actionPerformed( ActionEvent event )
      {
         JOptionPane.showMessageDialog( ButtonTest.this,
            "你按下的是:  " + event.getActionCommand() );
      } 
   } // end private inner class ButtonHandler 
} // end class ButtonTest

 

比较经常使用的控件 

 

JLabel 

  JLabel label1 = new JLabel( "用户名:" ); 

 

JTextField

 

 

 textField1 = new JTextField( 10 );  container.add( textField1 );

 

 

JPasswordField 

看不到输入

 

ImageIcon,JLabel

 

Icon bug = new ImageIcon( getClass().getResource("czims.jpg" ));
JLabel label2 = new JLabel( "照片:" , bug, SwingConstants.LEFT );
//设置label2的文本相对于图片的位置:水平方向居中对齐,垂直方向在图片的底部
label2.setHorizontalTextPosition( SwingConstants.CENTER );
label2.setVerticalTextPosition( SwingConstants.BOTTOM );
container.add( label2 );

 

JTextField

textField3 = new JTextField( "显示用户名或口令", 30 );
textField3.setEditable( false ); //设置不能修改
container.add( textField3 );

 

JTextArea

    Box box = Box.createHorizontalBox();
      //set up textArea1
      String string = "This is a demo string to\\n" + 
         "illustrate  textarea programming \\n" ;
      textArea1 = new JTextArea( string, 5, 12 );
      box.add( new JScrollPane( textArea1 ) );      
      
      copyButton = new JButton( "拷贝 >>>" );
      box.add( copyButton );
      copyButton.addActionListener(
         new ActionListener() {  // anonymous inner class
            // set text in textArea2 to selected text from textArea1
            public void actionPerformed( ActionEvent event )
            { 
                textArea2.setText( textArea1.getSelectedText() );
            }
         } // end anonymous inner class 
      ); // end call to addActionListener

      // set up textArea2
      textArea2 = new JTextArea( 5, 12 );
      textArea2.setEditable( false );
      box.add( new JScrollPane( textArea2 ) );
      // add box to content pane      
      container.add( box );      
      copyButton.addActionListener(
         new ActionListener() {  // anonymous inner class
            // set text in textArea2 to selected text from textArea1
            public void actionPerformed( ActionEvent event )
            { 
                textArea2.setText( textArea1.getSelectedText() );
            }
         } // end anonymous inner class 
      ); // end call to addActionListener

 

 

JCheckBox

 

      // create checkbox objects
      bold = new JCheckBox( "Bold" ,true);
      container.add( bold );     

      italic = new JCheckBox( "Italic" );
      container.add( italic );

      // register listeners for JCheckBoxes
      CheckBoxHandler handler = new CheckBoxHandler();
      bold.addItemListener( handler );
      italic.addItemListener( handler );
   private class CheckBoxHandler implements ItemListener {
      private int valBold = Font.PLAIN;
      private int valItalic = Font.PLAIN;    
      public void itemStateChanged( ItemEvent event ) // respond to checkbox events
      {   
         if ( event.getSource() == bold )   // process bold checkbox events
            valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN;            
         if ( event.getSource() == italic )   // process italic checkbox events
            valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN; 
         // set text field font
         field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); 
      } // end method itemStateChanged 
   } // end private inner class CheckBoxHandler

 

JRadioButton 

 

 

 

  

 // create radio buttons
      maleButton = new JRadioButton( "男", true );
      container.add( maleButton );

      womenButton = new JRadioButton( "女", false );
      container.add( womenButton );
      // create logical relationship between JRadioButtons
      radioGroup = new ButtonGroup();
      radioGroup.add( maleButton );
      radioGroup.add( womenButton );
          
      // register events for JRadioButtons
      maleButton.addItemListener( new RadioButtonHandler(  ) );
      womenButton.addItemListener( new RadioButtonHandler(  ) );      
      // set up JTextField
      field = new JTextField( "性别初值是: 男" );
      container.add( field ); 
   private class RadioButtonHandler implements ItemListener { 
      // handle radio button events
      public void itemStateChanged( ItemEvent event )
      {
         if (event.getItem()==maleButton)
          field.setText( "性别值是: 男" );
         else if (event.getItem()==womenButton)
         field.setText( "性别值是: 女" ); 
      } 
   } // end private inner class RadioButtonHandler

 

ComboBoxTest

 

 

 

private String names[] =
{ "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };
private Icon icons[] = new ImageIcon[names.length];  

      imagesComboBox = new JComboBox( names );
      imagesComboBox.setMaximumRowCount( 3 ); //设置允许显示的最大行数
      imagesComboBox.addItemListener( 
         new ItemListener() {  // anonymous inner class  
            // handle JComboBox event
            public void itemStateChanged( ItemEvent event )
            { 
               // determine whether check box selected
               if ( event.getStateChange() == ItemEvent.SELECTED )
                  label.setIcon( icons[ 
                     imagesComboBox.getSelectedIndex() ] );
            } 
         }  // end anonymous inner class 
      ); // end call to addItemListener 
      container.add( imagesComboBox ); 
      // set up JLabel to display ImageIcons
      for (int i=0;i<icons.length;i++) 
            icons[i]=new ImageIcon( getClass().getResource(names[ i ] ));
      label = new JLabel( icons[ 0 ] );
      container.add( label );

 

JList

 

   private final String colorNames[] = { "Black", "Blue", "Cyan", 
      "Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
      "Orange", "Pink", "Red", "White", "Yellow" };

   private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, 
      Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, 
      Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, 
      Color.YELLOW };

      // create a list with items in colorNames array
      colorList = new JList( colorNames );
      colorList.setVisibleRowCount( 5 );                  //设置在列表中显示的预定行数,
      colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );// 允许单项选择

      // add a JScrollPane containing JList to content pane
      container.add(new JLabel("请选择颜色,以控制JFrame背景色"));
      container.add( new JScrollPane( colorList ) );
      colorList.addListSelectionListener( 
         new ListSelectionListener() {  // anonymous inner class   
            // handle list selection events
            public void valueChanged( ListSelectionEvent event )
            {
               container.setBackground( 
               colors[ colorList.getSelectedIndex() ] );
            } 
         } // end anonymous inner class 
      ); // end call to addListSelectionListener

 

 

flowlayout

 

 

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FlowLayoutDemo extends JFrame {
   private JButton leftButton, centerButton, rightButton;
   private Container container;
   private FlowLayout layout;
   
   // set up GUI and register button listeners
   public FlowLayoutDemo()   {
      super( "FlowLayout布局管理" );
      layout = new FlowLayout();
      container = getContentPane();
      container.setLayout( layout );
      
      // set up leftButton and register listener
      leftButton = new JButton( "左对齐" );
      container.add( leftButton );
      leftButton.addActionListener(
         new ActionListener() { 
            public void actionPerformed( ActionEvent event )
            {  
               layout.setAlignment( FlowLayout.LEFT );
               // 重新对齐容器中的组件
               layout.layoutContainer( container );
            }

         } // end anonymous inner class

      ); // end call to addActionListener

      // set up centerButton and register listener
      centerButton = new JButton( "中心对齐" );
      container.add( centerButton );
      centerButton.addActionListener( 
         new ActionListener() {  // anonymous inner class 
            // process centerButton event  
            public void actionPerformed( ActionEvent event )
            {
               layout.setAlignment( FlowLayout.CENTER );               
               layout.layoutContainer( container );
            }
         }
      );

      // set up rightButton and register listener
      rightButton = new JButton( "右对齐" );
      container.add( rightButton );
      rightButton.addActionListener(

         new ActionListener() {  // anonymous inner class

            // process rightButton event  
            public void actionPerformed( ActionEvent event )
            {
               layout.setAlignment( FlowLayout.RIGHT );
               layout.layoutContainer( container );
            }
         }
      );

      setSize( 300, 75 );
      setVisible( true );

   } // end constructor FlowLayoutDemo
  
   public static void main( String args[] )
   { 
      FlowLayoutDemo application = new FlowLayoutDemo();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

} 

 

BorderLayout

 

// Demonstrating BorderLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BorderLayoutDemo extends JFrame implements ActionListener {
   private JButton buttons[];
   private final String names[] = { "North", "South", 
      "East", "West", "Center" };
   private BorderLayout layout;
   private Container container;

   // set up GUI and event handling
   public BorderLayoutDemo()
   {
      super( "BorderLayout布局管理" );

      layout = new BorderLayout( 5, 5 ); // 5 pixel gaps

      // get content pane and set its layout
      container = getContentPane();
      container.setLayout( layout );

      // instantiate button objects
      buttons = new JButton[ names.length ];

      for ( int count = 0; count < names.length; count++ ) {
         buttons[ count ] = new JButton( names[ count ] );
         buttons[ count ].addActionListener( this );
      }

      // place buttons in BorderLayout; order not important
      container.add( buttons[ 0 ], BorderLayout.NORTH ); 
      container.add( buttons[ 1 ], BorderLayout.SOUTH ); 
      container.add( buttons[ 2 ], BorderLayout.EAST );  
      container.add( buttons[ 3 ], BorderLayout.WEST );  
      container.add( buttons[ 4 ], BorderLayout.CENTER ); 

      setSize( 310, 200 );
      setVisible( true );

   }    
   public void actionPerformed( ActionEvent event )
   {
      for ( int count = 0; count < buttons.length; count++ )

         if ( event.getSource() == buttons[ count ] )
            buttons[ count ].setVisible( false );
         else
            buttons[ count ].setVisible( true );

      // re-layout the content pane
      layout.layoutContainer( container );
   }

   public static void main( String args[] )
   { 
      BorderLayoutDemo application = new BorderLayoutDemo();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

} // end class BorderLayoutDemo

 

GridLayout

 

 

// Demonstrating GridLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridLayoutDemo extends JFrame implements ActionListener {
   private JButton buttons[];
   private final String names[] = 
      { "one", "two", "three", "four", "five", "six" };
   private boolean toggle = true;
   private Container container;
   private GridLayout grid1, grid2;

   // set up GUI
   public GridLayoutDemo()
   {
      super( "GridLayout布局管理的应用" );

      // set up layouts
      grid1 = new GridLayout( 2, 3, 5, 5 ); //建立2*3网格,单元间隔为5像素
      grid2 = new GridLayout( 3, 2 );       //建立3*2网格,单元间隔为5像素

      // get content pane and set its layout
      container = getContentPane();
      container.setLayout( grid1 );

      // create and add buttons
      buttons = new JButton[ names.length ];

      for ( int count = 0; count < names.length; count++ ) {
         buttons[ count ] = new JButton( names[ count ] );
         buttons[ count ].addActionListener( this );
         container.add( buttons[ count ] );
      }

      setSize( 300, 150 );
      setVisible( true );

   } // end constructor GridLayoutDemo

   // handle button events by toggling between layouts
   public void actionPerformed( ActionEvent event )
   { 
      if ( toggle )
         container.setLayout( grid2 );
      else
         container.setLayout( grid1 );

      toggle = !toggle;            
      container.validate();   
   }

   public static void main( String args[] )
   {
      GridLayoutDemo application = new GridLayoutDemo();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   } 

} // end class GridLayoutDemo

 

CardLayout

 

 

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
public class CardLayoutDemo extends JFrame { 
  
  JPanel pleft; 
  JPanel pright;
  CardLayout card; 
  public CardLayoutDemo() 
  { 
   this.setBounds(80,60,600,300); 
   Container c=this.getContentPane(); 
   c.setLayout(new BorderLayout());
   
   pleft=new JPanel();  
        
   pleft.setBackground(Color.red);
   card=new CardLayout(10,10);
   pleft.setLayout(card); 
   JButton [] b=new JButton[10]; 
   for(int i=0;i<10;i++) 
   { 
    b[i]=new JButton("第"+i+"个Button"); 
    b[i].setFont(new Font("Helvetica", Font.PLAIN, 18));
    pleft.add("card"+i,b[i]); 
   }    
   
   
   pright=new JPanel(); 
   pright.setBackground(Color.blue);    
   pright.setLayout(new FlowLayout()); 
   
   JButton b1=new JButton("下一个按钮");   
   b1.addActionListener(new ActionListener()
   { public void actionPerformed(ActionEvent e) 
    { 
     card.next(pleft); 
    } 
   } ); 
   pright.add(b1); 
   c.add(pleft,BorderLayout.CENTER); 
   c.add(pright,BorderLayout.EAST);  
   
  } 
  public static void main(String []args) 
  { 
   CardLayoutDemo f=new CardLayoutDemo(); 
   f.setVisible(true);         
   f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
  } 
 }

GridBagLayout

 

 

// Demonstrating GridBaglayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GridBagDemo extends JFrame { 
   private GridBagLayout layout;
   private GridBagConstraints constraints;
   private Container container;
    
   // set up GUI
   public GridBagDemo()
   {
      super( "GridBag布局应用" );

      container = getContentPane();
      layout = new GridBagLayout();
      container.setLayout( layout );   

      // instantiate container. constraints
      constraints = new GridBagConstraints();
      constraints.fill = GridBagConstraints.BOTH;
      constraints.weightx = 1.0;    // can grow wider
      makebutton("Button1");
      makebutton("Button2");
      makebutton("Button3");

      constraints.gridwidth = GridBagConstraints.REMAINDER; //end row
      makebutton("Button4");

      constraints.weightx = 0.0;   //reset to the default,and gridwidth is  REMAINDER 
         makebutton("Button5"); //another row

        constraints.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row
         makebutton("Button6");

        constraints.gridwidth = GridBagConstraints.REMAINDER; //end row
         makebutton("Button7");

        constraints.gridwidth = 1;              //reset to the default
        constraints.gridheight = 2;
       constraints.weighty = 1.0;         //  can grow taller
       makebutton("Button8");

       constraints.weighty = 0.0;           //reset to the default
        constraints.gridwidth = GridBagConstraints.REMAINDER; //end row
        constraints.gridheight = 1;           //reset to the default
       makebutton("Button9");
       makebutton("Button10");
       
      setSize( 400, 200 );
      setVisible( true );
  
   }  // end constructor
   
   // add a component to the container
   private void makebutton(String name) {
         JButton button = new JButton(name);
         button.setFont(new Font("Helvetica", Font.PLAIN, 18));
         layout.setConstraints(button, constraints);
         container.add(button);
   }   

   public static void main( String args[] )
   {
      GridBagDemo application = new GridBagDemo();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

}  

 

JPanel

 

 

// Using a customized Panel object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// A customized JPanel class
class CustomPanel extends JPanel {
   
   private int shape; 
   // use shape to draw an oval or rectangle
   public void paintComponent( Graphics g )
   {
      super.paintComponent( g );
      g.setColor(Color.red);
      if ( shape == 1 )
         g.fillOval( 50, 10, 60, 60 );
      else if ( shape == 2 )
         g.fillRect( 190, 10, 60, 60 );
   } 
   // set shape value and repaint CustomPanel
   public void draw( int shapeToDraw )
   {
      shape = shapeToDraw;
      repaint();
   } 
} // end class CustomPanel 
public class CustomPanelTest extends JFrame {
   private JPanel buttonPanel;
   private CustomPanel myPanel;
   private JButton circleButton, squareButton; 
   public CustomPanelTest()
   {
      super( "创建定制JPanel类" ); 
      // create custom drawing area
      myPanel = new CustomPanel();   
      myPanel.setBackground( Color.GREEN ); 
      // set up squareButton
      squareButton = new JButton( "画正方型" );
      squareButton.addActionListener( 
         new ActionListener() {  // anonymous inner class  
            // draw a square
            public void actionPerformed( ActionEvent event )
            {
               myPanel.draw(2);
            } 
         } // end anonymous inner class 
      ); // end call to addActionListener 
      circleButton = new JButton( "画圆型" );
      circleButton.addActionListener( 
         new ActionListener() {  // anonymous inner class  
            // draw a circle
            public void actionPerformed( ActionEvent event )
            {
               myPanel.draw( 1 );
            } 
         } // end anonymous inner class 
      ); // end call to addActionListener

      // set up panel containing buttons
      buttonPanel = new JPanel();
      buttonPanel.setLayout( new GridLayout( 1, 2 ) );
      buttonPanel.add( circleButton );
      buttonPanel.add( squareButton );

      // attach button panel & custom drawing area to content pane
      Container container = getContentPane();
      container.add( myPanel, BorderLayout.CENTER );  
      container.add( buttonPanel, BorderLayout.SOUTH );

      setSize( 300, 150 );
      setVisible( true );

   } // end constructor CustomPanelTest

   public static void main( String args[] )
   {
      CustomPanelTest application = new CustomPanelTest();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

} // end class CustomPanelTest

 

 

JFrame

 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

 public class FrameTest
 {
    public static void main (String args[]) 
     {
         JFrame f = new JFrame ("JFrame Example"); 
         Container c = f.getContentPane(); 
         c.setLayout (new FlowLayout()); 
         c.add (new JLabel ("这是一个JFrame的一般示例!")); 
         f.setSize (300, 70);    
         f.show();
         f.addWindowListener(new WindowAdapter() 
         {
             public void windowClosing(WindowEvent e) 
             {
                 System.exit(0); 
             } 
         } );
     }
} 

 

 

 

 

布局

  Container container = get ContentPane();
  container.setLayout( new FlowLayout() ); 

 

添加监听器

   ButtonHandler handler = new ButtonHandler();
plainButton.addActionListener( handler );
 
TextFieldHandler handler = new TextFieldHandler();
      textField1.addActionListener( handler );  

   private class TextFieldHandler implements ActionListener { 
      // process textfield events
      public void actionPerformed( ActionEvent event )
      {
         String string = ""; 
         // user pressed Enter in JTextField textField1
         if ( event.getSource() == textField1 )
            string = "textField1: " + event.getActionCommand(); 
         // user pressed Enter in JTextField passwordField
         else if ( event.getSource() == passwordField ) {
            string = "passwordField: " + 
               new String( passwordField.getPassword() );
         } 
         textField3.setText( string ); 
      } // end method actionPerformed 
   } // end private inner class TextFieldHandler

 

 

设置大小是否可见

   setSize( 275, 100 );
   setVisible( true );

 

以上是关于Java-GUI的主要内容,如果未能解决你的问题,请参考以下文章

Java基础练习题12--Java-GUI制作一个模仿聊天群聊静态页面

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板