[英]Java - Updating a GUI made in Swing
我正在嘗試創建一個只有2個元素的簡單GUI表單 - 一個簡單的標簽和一個按鈕。 按鈕上顯示的文字是“開始”。 標簽默認顯示為0。
當我單擊“開始”按鈕時,將執行以下操作:
我正在Netbeans中開發我的應用程序。
如上圖所示,有2個.java文件
AGC.java的內容是:
public class AGC extends javax.swing.JFrame
{
public AGC()
{
initComponents();
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new AGC().setVisible(true);
}
});
}
private javax.swing.JButton btnStartStop; // name of start stop button
private javax.swing.JLabel lblCounter; // name of the label
}
Main.java的內容是:
public class Main
{
public static int count = 0;
public static boolean started = false;
}
我想實現以下邏輯:
private void btnStartStopMouseClicked(java.awt.event.MouseEvent evt)
{
if (Main.stared == true)
{
// logic to start counting
}
else
{
// logic to stop counting
}
}
我的問題是:
請幫助。 非常感謝工作代碼。 提前致謝。
松鴉
只需使用javax.swing.Timer ,並制作一個ActionListener ,即可為您完成此任務。 給我一個工作代碼示例10分鍾:-)
這是一個示例程序以獲得進一步的幫助:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UpdateWithTimer extends JFrame
{
private Timer timer;
private JButton startStopButton;
private JLabel changingLabel;
private int counter = 0;
private boolean flag = false;
private ActionListener timerAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
counter++;
changingLabel.setText("" + counter);
}
};
private ActionListener buttonAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!flag)
{
startStopButton.setText("STOP TIMER");
timer.start();
flag = true;
}
else if (flag)
{
startStopButton.setText("START TIMER");
timer.stop();
flag = false;
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
changingLabel = new JLabel("" + counter);
contentPane.add(changingLabel);
startStopButton = new JButton("START TIMER");
startStopButton.addActionListener(buttonAction);
add(contentPane, BorderLayout.CENTER);
add(startStopButton, BorderLayout.PAGE_END);
timer = new Timer(1000, timerAction);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new UpdateWithTimer().createAndDisplayGUI();
}
});
}
}
如果您希望計數器再次恢復為0,則在停止計時器時,只需添加即可
else if (flag)
{
startStopButton.setText("START TIMER");
timer.stop();
flag = false;
counter = 0;
changingLabel.setText("" + counter);
}
這部分是buttonAction
的actionPerformed(...)
方法。
好的,我建議看一下SwingWorker 。 你可以擴展SwingWorker並在doBackground()中使用Thread.sleep(1000);
執行a while(!isCancelled())
循環Thread.sleep(1000);
執行睡眠后,您只需觸發一個屬性更改,該屬性更改會增加標簽的值。
每當您按下停止按鈕時,只需取消當前的揮桿工作人員即可。 當您按下開始按鈕時,只需execute()
swing工作者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.