java 向 JComboBox 和 JTextField 添加标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13746933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:51:33  来源:igfitidea点击:

Adding a label to a JComboBox and JTextField

javaswingjtextfieldjcombobox

提问by Ikemesit Ansa

Hi I am having trouble adding labels to my combo box and textfield.It compiles fine but only shows the boxes but without labels.

嗨,我在向我的组合框和文本字段添加标签时遇到了问题。它编译得很好,但只显示框但没有标签。

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

public class AreaFrame2  
{  

   public static void main(String[]args)  
   { 

      //Create array containing shapes  
      String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};  

      //Use combobox to create drop down menu
      JComboBox comboBox=new JComboBox(shapes);
      JPanel panel1 = new JPanel(); 
      JLabel label1 = new JLabel("Select shape:");
      panel1.add(label1);
      comboBox.add(panel1);
      JButton button = new JButton("GO");
      JTextField text = new JTextField(20);

      //Create a JFrame that will be use to put JComboBox into it 
      JFrame frame=new JFrame("Area Calculator Window");  
      frame.setLayout(new FlowLayout()); //set layout
      frame.add(comboBox);//add combobox to JFrame
      text.setLocation(100,100);
      frame.add(text);
      frame.add(button);

      //set default close operation for JFrame 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      //set JFrame ssize 
      frame.setSize(250,250);  

      //make JFrame visible. So we can see it 
      frame.setVisible(true);  

   }  
}  

回答by ben75

I think the following code will produce more or less what you expect.

我认为以下代码或多或少会产生您期望的结果。

    public static void main(String[]args)
{
    //Create array containing shapes
    String[] shapes ={"(no shape selected)","Circle","Equilateral Triangle","Square"};

    //Use combobox to create drop down menu
    JComboBox comboBox=new JComboBox(shapes);
    JPanel panel1 = new JPanel(new FlowLayout());
    JLabel label1 = new JLabel("Select shape:");
    panel1.add(label1);
    panel1.add(comboBox);

    JButton button = new JButton("GO");
    JTextField text = new JTextField(20);
    //Create a JFrame that will be use to put JComboBox into it
    JFrame frame=new JFrame("Area Calculator Window");
    frame.setLayout(new FlowLayout()); //set layout
    frame.add(panel1);
    frame.add(text);
    frame.add(button);
    //set default close operation for JFrame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //set JFrame ssize
    frame.setSize(250,250);

    //make JFrame visible. So we can see it
    frame.setVisible(true);
}