抱歉打擾所有人。Java Swing按鈕actionEvent
總體問題:我試圖打開一個對話框,讓用戶輸入的東西然後將其關閉
問題: - 一個功能不被稱爲(我認爲) - 主要的問題是當我使用調試它工作正常所以它很難找到問題
我在JButtons有問題, 它工作在調試但不正常運行。這可能是因爲我使用了無限循環。網上有人建議我使用SwingUtilities類的,但沒有工作(至少我不認爲
/**
*
* @author Deep_Net_Backup
*/
public class butonTest extends JFrame {
String name;
boolean hasValue;
//name things
private JLabel m_nameLabel;
private JTextField m_name;
//panel
private JPanel pane;
//button
private JButton m_submit;
//action listener for the button submit
class submitListen implements ActionListener {
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
}
}
//constructor
public butonTest(){
//normal values
name = null;
hasValue = false;
//create the defauts
m_nameLabel = new JLabel("Name:");
m_name = new JTextField(25);
pane = new JPanel();
m_submit = new JButton("Submit");
m_submit.addActionListener(new submitListen());
//
setTitle("Create Cat");
setSize(300,200);
setResizable(false);
//add components
pane.add(m_nameLabel);
pane.add(m_name);
pane.add(m_submit);
add(pane);
//last things
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//submit
private void submit()
{
System.out.println("submit");
name = m_name.getText();
hasValue = true;
}
//hasValue
public boolean hasValue()
{
return(hasValue);
}
//get the text name
public String getName()
{
return(name);
}
public void close()
{
setVisible(false);
dispose();
}
public static void main(String[] args)
{
/* Test 1
boolean run = true;
String ret = new String();
butonTest lol = new butonTest();
while(run)
{
if(lol.hasValue())
{
System.out.println("Done");
run = false;
ret = new String(lol.getName());
lol.close();
}
}
System.out.println(ret);*/
//Tset 2
/*
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
butonTest lol = new butonTest();
if(lol.hasValue())
{
System.out.println(lol.getName());
}
}
});*/
}
}
編輯: 如何它不工作:當我運行測試程序將打印測試,然後提交它應該將hasValue更改爲true,這將會(希望)允許if語句運行以打印完成。這不會發生。
編輯2: 我剛剛添加了幾行以進一步測試2打印,這似乎解決了這個問題(但是這很糟糕) System.out.println(「hasValue」+ hasValue); - > hasValue()函數 System.out.println(「set to t後悔」); - > submit()函數
它是如何工作的?請給我們重要的細節,並假設我們對您的問題或代碼一無所知。 –
你想做什麼?你只是想關閉對話框? –
Test1,你的while循環阻塞了UI。 Test2,你調用'hasValue()'只會影響你調用它的_one_時間,這是錯誤的 –