第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按下 GUI 按鈕,從數(shù)組中選擇一個隨機單詞并將其放置在 JLabel 上

按下 GUI 按鈕,從數(shù)組中選擇一個隨機單詞并將其放置在 JLabel 上

達令說 2022-11-02 10:42:37
我對此GUI代碼有疑問。如何出現(xiàn)在JLabel隨機詞上?基本上,該程序的目的是創(chuàng)建一個GUI按鈕,單擊該按鈕時從數(shù)組中選擇一個隨機單詞并將其放入JLabel.我遇到的麻煩是讓單詞出現(xiàn)在 上JLabel,我不太確定應該怎么做。import java.awt.Color;import java.awt.Dimension;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;public class GuiQuiz {    public static void main(String[] args) {        JFrame frame = new JFrame("Button Example");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        JPanel mainPanel = new JPanel();        mainPanel.setBackground(Color.BLUE);        mainPanel.setPreferredSize(new Dimension(500, 500));        JPanel subPanel1 = new JPanel();        subPanel1.setBackground(new Color(134, 179, 0));        subPanel1.setPreferredSize(new Dimension(150, 100));        subPanel1.add(new JLabel("Random word here"));        String[] names = { "Class", "Charger", "Pencil", "Dog", "Robot", "Ninja", "Teacher", "Video", "Book",            "Computer" };        JButton button = new JButton("Generates a random word");        button.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                String name = names[(int) (Math.random() * names.length)];                 ((JButton) e.getSource()).setText(name);            }        });        mainPanel.add(button);        mainPanel.add(subPanel1);        frame.getContentPane().add(mainPanel);        frame.pack();        frame.setVisible(true);    }}
查看完整描述

1 回答

?
交互式愛情

TA貢獻1712條經(jīng)驗 獲得超3個贊

您JLabel在寫作時聲明匿名:


subPanel1.add(new JLabel("Random word here"));

您需要將其設置為變量:


JLabel label = new JLabel("Random word here");

subPanel1.add(label);

現(xiàn)在你有你button自己的ActionListener:


button.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {

        String name = names[(int) (Math.random() * names.length)]; 

        ((JButton) e.getSource()).setText(name);

    }

});

而且您正在設置JButton的文本,而不是標簽,因此我們需要將其更改為:


button.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {

        String name = names[(int) (Math.random() * names.length)]; 

        label.setText(name);

    }

});

那應該做你想做的事,我沒有嘗試過,但它在我的腦海中有效。

附加提示:


查看完整回答
反對 回復 2022-11-02
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號