簡體   English   中英

涉及Swing的EDT的線程錯誤

[英]Thread Errors involving Swing's EDT

正如您從我的代碼中看到的那樣,我在這里完全缺少一個完整的概念。 我的目標是讓用戶輸入:

Jbutton文本字段:文本方向和助記符

我將該信息傳遞給我的Button類,該類檢查錯誤並返回已經定義的按鈕。

然后,根據用戶要求,使用上述按鈕填充JFrame。

BASIC顯然是一個課程問題,但我的智慧到此為止。 這是我第一次尋求幫助,因此請放心。

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;


/**
 * This class will create a button using the Button class and with user input to define the instance
 * of the Button Class.
 * 
 */
public class CreateButton extends JPanel
{
    // instance variables 
    private static String userIn; // user input
    private static Button userButton; // button to be manipulated
    public static JButton createdButton; // finished button



    /**
     * Contructor for the CreateButton class.
     */
    public static void main (String [] args)
    {

            System.out.println("\nThis program will create a button with some input for you.");
            System.out.println("What would you like to call this button?");

            userIn = StringIn.get();

            userButton = new Button();
            userButton.buttonText(userIn);

            System.out.println("\nYou can orient your text on the button in the vertical and");
            System.out.println("horizontal axis. We will start with the vertical. Where would you like");
            System.out.println("the text, on the top, center, or bottom?");

            userIn = StringIn.get();

            String vertical = userIn;

            System.out.println("\nNext let's select the horizontal alignment. Would you like the text");
            System.out.println("aligned to the left, center, or right?");

            userIn = StringIn.get();

            String horizontal = userIn;

            userButton.textPosition(vertical,horizontal);

            System.out.println("\nFinally let's add a mnemonic or hotkey to the button. Pick a letter");
            System.out.println("from a-z on the keyboard and you can activate the button by pushing");
            System.out.println("ALT + your letter of choice. Please enter your letter:");

            userIn = StringIn.get();

            userButton.buttonMnemomic(userIn);

            System.out.println("\nGreat let's create and see this button.");


            javax.swing.SwingUtilities.invokeLater(new Runnable() 
            {
                public void run() 
                {
                   createAndShowGUI();
                }
            }); 

    }

     private static void createAndShowGUI() 
    {

        //Create and set up the window.
        JFrame frame = new JFrame("Create a Button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        CreateButton newContentPane =  new CreateButton();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);


        //Display the window.
        frame.pack();
        frame.setVisible(true);

    }
}

我的按鈕錯誤檢查器代碼如下:

import javax.swing.AbstractButton;
import javax.swing.JButton;


/**
 * This class will demonstrate the use of a button.
 * 
 */
public class Button                        
{
    // instance variables 
    protected JButton myButton; // button to be created and manipulated
    private String myButtonText; // text on the button
    private String myButtonVerticalTextPosition; 
    private String myButtonHorizontalTextPosition;
    private String myButtonMnemonic; // hotkey for the button

    /**
     * Constructor for objects of class Button
     */
    public Button()
    {

    }

    /**
     *Set button text. String input.
     */
    public void buttonText(String textIn)
    {
        myButtonText = textIn;
    }

    /**
     *Set button text position. String input for vertical (top, center, bottom) and horizontal
     *(left, center, right).
     */
    public void textPosition(String verticalIn, String horizontalIn)
    {
        myButtonVerticalTextPosition = verticalIn;

        boolean validInput = false;

        do
        {
            if  ((myButtonVerticalTextPosition.compareToIgnoreCase("top") == 0)||  
                 (myButtonVerticalTextPosition.compareToIgnoreCase("centre") == 0) ||
                 (myButtonVerticalTextPosition.compareToIgnoreCase("center") == 0) ||
                 (myButtonVerticalTextPosition.compareToIgnoreCase("bottom") == 0))
            {

                validInput = true;
            } else
            {

               System.out.println("\nPlease enter top, center, or bottom for vertical position:");
               myButtonVerticalTextPosition = StringIn.get();
            } 
        } while (validInput == false);

        myButtonHorizontalTextPosition = horizontalIn;

        validInput = false;

        do
        {
            if  ((myButtonHorizontalTextPosition.compareToIgnoreCase("left") == 0) ||  
                 (myButtonHorizontalTextPosition.compareToIgnoreCase("centre") == 0) ||
                 (myButtonHorizontalTextPosition.compareToIgnoreCase("center") == 0) ||
                 (myButtonHorizontalTextPosition.compareToIgnoreCase("right") == 0))
            {

                validInput = true;
            } else 
            {

                System.out.println("\nPlease enter left, center, or right for horizontal position:");
                myButtonHorizontalTextPosition = StringIn.get();
            } 
        } while (validInput == false);
    }

    /**
     *Set button mnemomic. String input for mnemomic [a-z].
     */
    public void buttonMnemomic(String mnemomicIn)
    {
        myButtonMnemonic = mnemomicIn;
        boolean validInput = false;

        do
        {
            if  (myButtonMnemonic.length() > 1)
            {
                System.out.println("\nPlease enter a letter from a-z: ");
                myButtonMnemonic = StringIn.get();
            } else if (!myButtonMnemonic.matches("^[a-zA-Z]+$"))
            {
                System.out.println("\nPlease enter a letter from a-z: ");
                myButtonMnemonic = StringIn.get();
            } else if ((myButtonMnemonic.length() == 1) && 
                       (myButtonMnemonic.matches("^[a-zA-Z]+$")))
            {
                validInput = true;
            }
        } while (validInput == false);
    }

    /**
     *Create button. Void method to create the button to the variables provided.
     */
    public void createButton()
    {
        // create new button

        myButton = new JButton(myButtonText);

        // set text position

        switch (myButtonVerticalTextPosition)
        {
            case "top":
                myButton.setVerticalTextPosition(AbstractButton.TOP);
                break;
            case "centre":
                myButton.setVerticalTextPosition(AbstractButton.CENTER);
                break;
            case "center":
                myButton.setVerticalTextPosition(AbstractButton.CENTER);
                break;
            case "bottom":
                myButton.setVerticalTextPosition(AbstractButton.BOTTOM);
                break;
            default:
                System.err.format("%n%s is an invalid entry.", myButtonVerticalTextPosition);
                break;
        }

        switch (myButtonHorizontalTextPosition)
        {
            case "left":
                myButton.setHorizontalTextPosition(AbstractButton.LEADING);
                break;
            case "centre":
                myButton.setHorizontalTextPosition(AbstractButton.CENTER);
                break;
            case "center":
                myButton.setHorizontalTextPosition(AbstractButton.CENTER);
                break;
            case "right":
                myButton.setHorizontalTextPosition(AbstractButton.TRAILING);
                break;
            default:
                System.err.format("%n%s is an invalid entry.", myButtonVerticalTextPosition);
                break;
        }

        // set button mnemonic

        StringBuilder hotKey = new StringBuilder("KeyEvent.VK_");
        hotKey.append(myButtonMnemonic.toUpperCase());
        myButton.setMnemonic(hotKey.charAt(0));

        // set tool tip text

        myButton.setToolTipText("Push the button. You know you want to.");
    }

    /**
     *Returns a JButton for the button type.
     */
    public JButton returnButton()
    {
        return myButton;
    }
}

所有這些都可以在添加“ createdButton”的部分完成。 如果我將其設置為默認按鈕,它將經歷所有動作並提出默認按鈕。

僅供參考,這是我的StringIn代碼:

import java.util.Scanner;
import java.io.IOException;

/**
 * This class will allow the user to type in string from the console.
 * 
 */

public class StringIn 
{
    // instance variables 
    private static String userIn;

    public static String get() 
    {

        try (Scanner in = new Scanner(System.in))
        {
            userIn = new String(in.nextLine()); // Read the string from console.
        }
        return userIn;

    }
}

對於StringIn類,只需執行以下操作:

    import java.util.Scanner;


    public class StringIn 
    {
        // instance variables 
        private static Scanner scanner = new Scanner(System.in);

        public static String get(){
            return scanner.nextLine();
        }
    }

編輯2:

好的,所以我將您的代碼復制到我的IDE中,並且得到的錯誤是源自您的StringIn類的錯誤。 (我實際上不記得了,但這並不重要。)

您的StringIn類應類似於上面的示例。

對於您的createAndShowGUI()函數:

    private static void createAndShowGUI() 
    {

        //Create and set up the window.
        JFrame frame = new JFrame("Create a Button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane. ( Why were you even doing this? )

        frame.add(createdButton); //( To display the actual button you need to
        //add it to the frame)

        //Display the window.
        frame.pack();
        frame.setVisible(true);

    }

那樣做^

我無法使與助記符相關的事情正常工作,並且我不想花太多時間在上面,因此我將其刪除。 方向的東西也不起作用。

將其放在main(String args [])的底部

    createdButton = userButton.createButton(); // Make createButton() return Button;

除了以下部分,您不需要在代碼中的任何位置使用JButton:

    public class Button extends JButton
    // And of course the import statement...

您可以使用Button.TOP而不是AbstractButton.TOP ,它會為您消除導入語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM