JFrame - 输出方法结果为JLabel

时间:2014-04-09 10:51:29

标签: java swing jframe jpanel

我为练习做了一个愚蠢的随机句子生成器,我现在试图让结果显示在JLabel中。我很困惑,在尝试按照一些教程将控制台输出到JTextArea或JLabel之后,我已经确定这不是我想要实现的目标。我只是想这样,当我点击我的按钮时,它运行wordGen类并将其结果输出到我的JLabel。

这是我的代码段:

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


public class HelloWorldGUI2 {

private static class HelloWorldDisplay extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
//          g.draw3DRect(20, 30, 100, 100, true);
    }

}

private static class ButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        return wordGen(); // This is me trying to get the button when clicked to run the wordGen class. Obviously completely wrong.
    }
}

public static class wordGen  {
    // Make three sets of words to choose from
    String[] wordListOne = {"24/7","Terrific","Time-tested","Returned","Tried","Intepreted","Ebay","Large","Small","Medium"};
    String[] wordListTwo = {"Oriented","Shared","Aligned","Targeted","Leveraged","Charged","Networked","Centric","Distributed","Postioned"};
    String[] wordListThree = {"Bush-beater","Pikestaff","Placket-racket","Hammer-handle","Quim-wedge","Creamstick","Tug-mutton","Kennel-raker","Testicles","Penis","Vagina","Breasts","TallyWhacker","Johnson","Meat","ClamFist","Binlid"};

    //find out how many words are in each list
    int oneLength = wordListOne.length;
    int twoLength = wordListTwo.length;
    int threeLength = wordListThree.length;

    //generate three random numbers
    int rand1 = (int) (Math.random() * oneLength);
    int rand2 = (int) (Math.random() * twoLength);
    int rand3 = (int) (Math.random() * threeLength);

    //now build a phrase
    String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];
}

public static void main(String[] args) {
    HelloWorldDisplay displayPanel = new HelloWorldDisplay();
    JButton okButton = new JButton("New Word Combo"); // Create new button
    okButton.setFont(new Font("Malina Light",Font.TRUETYPE_FONT,14)); // Assign     custom font to new button
    ButtonHandler listener = new ButtonHandler();
    okButton.addActionListener(listener);

    //Text Label - For the eventual output of the random sentence generator
    JLabel jLab = new JLabel(wordGen);

    JPanel content = new JPanel();
    content.setLayout(new BorderLayout());
    content.add(displayPanel, BorderLayout.CENTER);
    content.add(okButton, BorderLayout.SOUTH);
    content.add( jLab, BorderLayout.NORTH );

    JFrame window = new JFrame("GUI Test"); // Declaring the variable 'window'     to type JFrame and sets it to refer to a new window object within the statement
    window.setContentPane(content);
    window.setSize(250,150);
    window.setLocation(100,100);
    window.setVisible(true);

    }
}

无论如何,我为n00bish道歉,但这是我的迷你编程难题的最后一块!

4 个答案:

答案 0 :(得分:1)

首先,您无法在void方法中返回对象。所以你不能这样做:

public void actionPerformed(ActionEvent e) {
    return wordGen(); // This is me trying to get the button when clicked to run the wordGen class. Obviously completely wrong.
}

但你可以用另一种方式来实现你的目标,

您可以从anonymous班级直接创建一个ActionListener按钮,这样您就可以访问JLabel,然后添加要显示的文字

例如

JLabel jLab = new JLabel(wordGen);// note this Label should be final or an instance variable.
b.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        jLab.setText(new awordGen().getSomeText());// suppose you have getSomeText method.
    }
});

答案 1 :(得分:1)

您可以互换地使用类和方法。例如,wordGen是一个类,但您尝试调用它,就像它是一个方法一样。我更改了您的代码,因此您可以运行该示例。我还删除了不必要的代码。 HelloWorldDisplayButtonHandler似乎是无用的课程。我删除了它们,并清理了代码。完整的工作示例:

package proGui;

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


public class HelloWorldGUI2 {

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                showGUI(args);
            }
        });
    }

    public static void showGUI(String[] args) {
        JPanel displayPanel = new JPanel();
        JButton okButton = new JButton("New Word Combo"); // Create new button
        okButton.setFont(new Font("Malina Light", Font.TRUETYPE_FONT, 14)); // Assign     custom font to new button
        final JLabel jLab = new JLabel();
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jLab.setText(wordGen());
            }
        });

        //random sentence is set above, see jLab.setText(wordGen())
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(displayPanel, BorderLayout.CENTER);
        content.add(okButton, BorderLayout.SOUTH);
        content.add(jLab, BorderLayout.NORTH);

        JFrame window = new JFrame("GUI Test"); // Declaring the variable 'window'     to type JFrame and sets it to refer to a new window object within the statement
        window.setContentPane(content);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(250, 150);
        window.setLocation(100, 100);
        window.setVisible(true);

    }

    public static String wordGen() {
        // Make three sets of words to choose from
        String[] wordListOne = {"24/7", "Terrific", "Time-tested", "Returned", "Tried", "Intepreted", "Ebay", "Large", "Small", "Medium"};
        String[] wordListTwo = {"Oriented", "Shared", "Aligned", "Targeted", "Leveraged", "Charged", "Networked", "Centric", "Distributed", "Postioned"};
        String[] wordListThree = {"Bush-beater", "Pikestaff", "Placket-racket", "Hammer-handle", "Quim-wedge", "Creamstick", "Tug-mutton", "Kennel-raker", "Testicles", "Penis", "Vagina", "Breasts", "TallyWhacker", "Johnson", "Meat", "ClamFist", "Binlid"};

        //find out how many words are in each list
        int oneLength = wordListOne.length;
        int twoLength = wordListTwo.length;
        int threeLength = wordListThree.length;

        //generate three random numbers
        int rand1 = (int) (Math.random() * oneLength);
        int rand2 = (int) (Math.random() * twoLength);
        int rand3 = (int) (Math.random() * threeLength);

        //now build a phrase
        String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];
        return phrase;
    }


}

答案 2 :(得分:0)

全局声明JLabel jLab;

public static class wordGen
{
//your exact code
jLabl.setText(phrase);
}

答案 3 :(得分:0)

在您的代码中,wordGen应该是一个方法,而不是一个类。 jLab必须是HelloWorldGUI2中的一个字段,才能从ActionListener访问它。

public class HelloWorldGUI2 {

    private static JLabel jLab;

    private static class HelloWorldDisplay extends JPanel {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
//          g.draw3DRect(20, 30, 100, 100, true);
        }

    }

    private static class OkButtonActionListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String generatedPhrase = wordGen();
            jLab.setText(generatedPhrase);
        }
    }

    public static String wordGen() {
        // Make three sets of words to choose from
        String[] wordListOne = {"24/7", "Terrific", "Time-tested", "Returned", "Tried", "Intepreted", "Ebay", "Large", "Small", "Medium"};
        String[] wordListTwo = {"Oriented", "Shared", "Aligned", "Targeted", "Leveraged", "Charged", "Networked", "Centric", "Distributed", "Postioned"};
        String[] wordListThree = {"Bush-beater", "Pikestaff", "Placket-racket", "Hammer-handle", "Quim-wedge", "Creamstick", "Tug-mutton", "Kennel-raker", "Testicles", "Penis", "Vagina", "Breasts", "TallyWhacker", "Johnson", "Meat", "ClamFist", "Binlid"};

        //find out how many words are in each list
        int oneLength = wordListOne.length;
        int twoLength = wordListTwo.length;
        int threeLength = wordListThree.length;

        //generate three random numbers
        int rand1 = (int) (Math.random() * oneLength);
        int rand2 = (int) (Math.random() * twoLength);
        int rand3 = (int) (Math.random() * threeLength);

        //now build a phrase
        String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];
        return phrase;
    }

    public static void main(String[] args) {
        HelloWorldDisplay displayPanel = new HelloWorldDisplay();
        jLab = new JLabel();
        JButton okButton = new JButton("New Word Combo"); // Create new button
        okButton.setFont(new Font("Malina Light", Font.TRUETYPE_FONT, 14)); // Assign     custom font to new button
        okButton.addActionListener(new OkButtonActionListener());

        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(displayPanel, BorderLayout.CENTER);
        content.add(okButton, BorderLayout.SOUTH);
        content.add(jLab, BorderLayout.NORTH);

        JFrame window = new JFrame("GUI Test"); // Declaring the variable 'window'     to type JFrame and sets it to refer to a new window object within the statement
        window.setContentPane(content);
        window.setSize(250, 150);
        window.setLocation(100, 100);
        window.setVisible(true);

    }
}