我有以下代码来设置一个gui,使用JComboBox从用户输入源语言和目标语言,但在运行它时,除了显示按钮之外什么都没有,请提出建议。我已经在构造函数中完成了初始化和所有其他的东西。
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Insets;
import java.io.FileNotFoundException;
public class SrcAndTargLangInput implements ActionListener {
public static JFrame frame;
public static JComboBox sourcLang;
public static JComboBox targLang;
public static JLabel setSrcLang;
public static JLabel setTargLang;
public static JButton ok;
String[] lang = new String[2];
public SrcAndTargLangInput() {
ok = new JButton("Ok");
ok.setBounds(150, 400, 100, 50);
frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.getContentPane().add(ok);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Insets ins = frame.getInsets();
frame.setSize(400 + ins.left + ins.right, 500 + ins.bottom + ins.top);
setSrcLang = new JLabel("Source Language");
setSrcLang.setBounds(50, 100, 100, 40);
setTargLang = new JLabel("Target Language");
setTargLang.setBounds(50, 200, 100, 40);
String[] srcLangList = { "English", "Spanish", "French" };
sourcLang = new JComboBox(srcLangList);
sourcLang.setBounds(250, 100, 100, 40);
String[] targLangList = { "English", "Spanish", "French" };
targLang = new JComboBox(targLangList);
targLang.setBounds(250, 200, 100, 40);
frame.setVisible(true);
ok.addActionListener(this);
}
public static void main(String args[]) {
new SrcAndTargLangInput();
}
public void actionPerformed(ActionEvent e) {
lang[0] = (sourcLang.getSelectedItem().toString());
lang[1] = (targLang.getSelectedItem().toString());
frame.setVisible(false);
}
}
你有没有先检查一下你的代码?您已经将JButton
添加到框架的内容窗格中,但还没有添加JComboBox
。也不需要调用frame.setVisible(true);
两次;当你把元素添加到框架中时,就调用它。
最后,您不应该在事件分派线程(EDT)之外运行您的Swing GUI代码,否则您以后可能会遇到线程问题。将main方法更改为:
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SrcAndTargLangInput();
}
}
}