嗨,我正在尝试创建一个由 JComboBox 和 JTextField 组成的界面。我已经整理了向 JComboBox 添加标签的代码,但在向文本字段添加标签时遇到了问题。任何帮助将不胜感激。
import javax.swing. *;
import java.awt.event. *;
import java.awt.FlowLayout;
import java.lang.Math;
public class AreaFrame3 extends JFrame
{
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()); //set frame layout
JLabel label1 = new JLabel("Select shape:");
panel1.add(label1);
panel1.add(comboBox);
JTextField text = new JTextField(10); //create text field
JFrame frame=new JFrame("Area Calculator Window");//create a JFrame to put combobox
frame.setLayout(new FlowLayout()); //set layout
frame.add(panel1);
frame.add(text);
JButton button = new JButton("GO"); //create GO button
frame.add(button);
//set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//set JFrame ssize
frame.setSize(400,250);
//make JFrame visible. So we can see it
frame.setVisible(true);
}
}
最佳答案
这是一种方法。只需按照适当的顺序将所有小部件放入 panel1
中即可。
从长远来看,这可能不太容易维护,您可能希望拥有一个比 FlowLayout
更好的 LayoutManager,但如果您只是想学习 Swing,这可能是一个好的开始。如果你觉得FlowLayout不够好,可以看看LayoutManager教程。我个人最喜欢的是:BorderLayout
和 GridBagLayout
。 MigLayout
可能也是一个不错的,但我从未使用过它,而且它不是 JVM 的一部分。
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AreaFrame3 {
protected void initUI() {
// 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);
JLabel label1 = new JLabel("Select shape:");
JPanel panel1 = new JPanel(new FlowLayout()); // set frame layout
JLabel label2 = new JLabel("Text label:");
JTextField text = new JTextField(10); // create text field
panel1.add(label1);
panel1.add(comboBox);
panel1.add(label2);
panel1.add(text);
JFrame frame = new JFrame("Area Calculator Window");// create a JFrame to put combobox
frame.setLayout(new FlowLayout()); // set layout
frame.add(panel1);
JButton button = new JButton("GO"); // create GO button
frame.add(button);
// set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
// make JFrame visible. So we can see it
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new AreaFrame3().initUI();
}
});
}
}
关于java - 向文本字段添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13762589/