我在刷新JComboBox
中的數據時遇到問題。如何刷新JComboBox數據?
有一個按鈕「Create
」其中有ActionListener
,它將項目添加到JComboBox
。
但是這些改變並沒有反映在GUI中:我仍然沒有看到新增加的項目。
repaint()
沒有幫助。
更新:這裏是(幾乎)完全GUI代碼:
public class Main extends JFrame implements ActionListener
{
static Connection conn;
static PreparedStatement ps = null;
static ResultSet res;
static Statement sta;
private final static int ITERATION_NUMBER = 1000;
public void GUI() throws SQLException {
setBounds(0, 0, 320, 240);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
close(ps);
close(res);
close(conn);
System.exit(0);
}
});
setMinimumSize(new Dimension(320, 240));
setResizable(false);
this.setTitle("Accounts");
JPanel panel = new JPanel();
GridLayout2 GL = new GridLayout2(4,3);
GL.setHgap(10);
panel.setLayout(GL);
Font font = new Font("Serif", Font.BOLD, 20);
Font font2 = new Font("Courier New", Font.BOLD, 16);
JLabel label1 = new JLabel("Username");
JLabel label2 = new JLabel("Password");
JLabel label3 = new JLabel("Controls");
label1.setFont(font2);
label2.setFont(font2);
label3.setFont(font2);
final JTextField username = new JTextField();
final JTextField password1 = new JPasswordField();
final JTextField password2 = new JPasswordField();
final JComboBox userBox1 = new JComboBox();
final JComboBox userBox2 = new JComboBox();
JButton create = new JButton("CREATE");
create.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try {
createUser(conn, username.getText(), password1.getText());
userBox1.addItem(username.getText());
userBox2.addItem(username.getText());
} catch (NoSuchAlgorithmException
| UnsupportedEncodingException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
userBox1.removeAllItems();
userBox2.removeAllItems();
res = (ResultSet) sta.executeQuery("SELECT LOGIN FROM ACCOUNTS");
String temp;
for (int i=0; res.next(); i++) {
temp = (String)res.getString("LOGIN");
userBox1.addItem(temp);
userBox2.addItem(temp);
}
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(username);
panel.add(password1);
panel.add(create);
panel.add(userBox1);
panel.add(password2);
panel.add(modify);
panel.add(userBox2);
panel.add(new JLabel(""));
panel.add(delete);
add(panel);
setVisible(true);
}
SOLUTION:添加password1.setText( 「」);剛剛「createUser」解決了問題!真奇怪,也許它在某種程度上刷新GUI ...
你能提供一些代碼嗎? – Jack
是否'refesh'是'JComboBox'是一個容器的'panel'或者frame。 – Subs
重繪幾乎是不需要的。組件知道何時需要重新繪製自己。 –