每次点击“加载”时,我都会尝试更新空的Jlabel。 JButton的。我已经向Jbutton添加了一个actionlistener,但由于某种原因,标签不会更新或使用setText(String)方法显示任何文本。
JLabel stupidLabel = new JLabel();
stupidLabel.setForeground(SystemColor.infoText);
stupidLabel.setFont(new Font("Arial", Font.PLAIN, 11));
stupidLabel.setBounds(71, 46, 167, 14);
panel.add(stupidLabel);'
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stupidLabel.setText("Update please");
}
});
load.setFont(new Font("Arial", Font.PLAIN, 11));
load.setBounds(189, 92, 89, 22);
contentPane.add(load);
似乎没有效果。
似乎有什么问题?有没有办法让标签每隔一秒左右自动更新一次,有效地完全不需要按钮?
答案 0 :(得分:2)
对我来说很好......
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JLabel stupidLabel = new JLabel(" ");
stupidLabel.setForeground(SystemColor.infoText);
stupidLabel.setFont(new Font("Arial", Font.PLAIN, 11));
add(stupidLabel, gbc);
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stupidLabel.setText("Update please");
}
});
load.setFont(new Font("Arial", Font.PLAIN, 11));
add(load, gbc);
}
}
}
考虑提供展示您问题的runnable example。这不是代码转储,而是您正在做的事情的一个示例,它突出了您遇到的问题。这将减少混淆和更好的响应