2014-04-09 5 views
0

Я сделал глупый генератор случайных предложений для практики, и теперь я пытаюсь получить результаты для отображения в JLabel. Я довольно застрял, и, пытаясь следовать некоторым учебным пособиям при получении консольного вывода в JTextArea или JLabel, я решил, что это не то, чего я пытаюсь достичь. Я просто хочу, чтобы, щелкнув по моей кнопке, он запускает класс wordGen и выводит результаты в мой JLabel.JFrame - результаты метода вывода в 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, но это последняя часть моей мини программирования головоломки!

ответ

1

Вы используете класс и метод взаимозаменяемые. Например, wordGen - это класс, но вы пытаетесь вызвать его, как если бы это был метод. Я изменил ваш код, поэтому вы можете запустить пример. Я также удалил ненужный код. HelloWorldDisplay и ButtonHandler кажутся бесполезными классами. Я удалил их и очистил код. Полный рабочий пример:

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; 
    } 


} 
+0

Блестящий, большое вам спасибо. Работает именно так, как я этого хотел! Теперь я перейду через ваше редактирование и обязательно пойму все! – c0d3n4m3

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. 
    } 
}); 
0

Declare JLabel jLab; глобально, то

public static class wordGen 
{ 
//your exact code 
jLabl.setText(phrase); 
} 
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); 

    } 
} 
+0

Благодарим вас за ввод! Я очень ценю это. – c0d3n4m3

Смежные вопросы