Java在按钮后更改JLabel的文本

时间:2016-11-25 15:32:28

标签: java jlabel settext

我正在努力学习Java,因此我只想尝试一些东西。现在,我在点击按钮后尝试更改JLabel的文本。我试过在这个网站上阅读它,但无法找到我出错的地方。我真的希望有人可以帮助我。

您可以在下面找到我的代码。我正在尝试的是按钮&#b1'单击,FirstText的文本更改为“Clicked!”#39;。但对我来说,屏幕保持不变,文字没有改变。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class vlaggenquiz extends JPanel implements ActionListener {
public JLabel FirstTitle, FirstText;
public JButton b1;

public vlaggenquiz() {
    super(new BorderLayout());

    //Maakt tekst en buttons aan voor eerste scherm
    JLabel FirstTitle = new JLabel ("TITLE!");
    JLabel FirstText = new JLabel ("Hello there!");
    b1 = new JButton ("Click");
    b1.addActionListener(this);


    //Bepaald tekstgrootte titel
    FirstTitle.setFont(new Font("Arial", Font.BOLD, 50));

    //Bepaald font tekst
    FirstText.setFont(new Font("Arial", Font.PLAIN, 15));

    //Centreert de teksten
    FirstTitle.setHorizontalAlignment(JLabel.CENTER);
    FirstText.setHorizontalAlignment(JLabel.CENTER);

    //Voegt beide teksten en button toe
    add(FirstTitle, BorderLayout.PAGE_START);
    add(FirstText, BorderLayout.CENTER);
    add(b1, BorderLayout.PAGE_END);

    //Voegt ruimte to aan de zijkanten binnen app
    setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}

public void actionPerformed(ActionEvent event) {
    FirstText.setText("Clicked!");
}

public static void createAndShowGUI() {
    JFrame frame = new JFrame("Vlaggenquiz");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComponent newContentPane = new vlaggenquiz();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.setSize(500, 500);

    frame.pack();
    frame.setVisible(true);
}

public static void main (String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

0 个答案:

没有答案