2012-08-26 2 views
0

제 코드에서 알 수 있듯이 전체적인 개념이 완전히 누락되었습니다.스윙의 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"를 추가하는 부분까지 작동합니다. 기본 버튼으로 만들면 모션을 거치며 기본 버튼이 표시됩니다. 단지 할

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; 

    } 
} 
+1

또한 'System.in'에 의존하지 않는 디자인을 고려하십시오. – trashgod

답변

0

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

Edit2가 :

은 참고이 내 StringIn 코드

좋아, 그래서 난 내 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); 

    } 

이 좋아하니 그^

내가 할 수없는 니모닉과 관련된 일들이 제대로 작동하려면, 내가 너무 많은 시간을 보내고 싶지 않아 도착 그것에, 그래서 나는 그들을 그냥 제거했습니다. 오리엔테이션도 작동하지 않았습니다.

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

당신은 Button.TOP를 사용할 수 있습니다

메인 (문자열 인수 [])

createdButton = userButton.createButton(); // Make createButton() return Button; 
당신은이 부분을 제외하고 어디에서나 코드에서의 JButton 필요하지 않습니다

가의 하단이 넣어 AbstractButton.TOP 대신 가져 오기 명령문을 제거합니다.

+0

[* 초기 스레드 *] (http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)도 참조하십시오. – trashgod

+0

@ user1555857 (runnable 내에서) createAndShowGUI 메소드를 호출하는 것이 적절하고 권장됩니다. 주 (主)가 EDT 내에서 호출 될 것이라는 보장은 없습니다 – MadProgrammer

+0

흠 ... 추가 된 지혜를 주셔서 감사합니다 :) 특정 프로그램의 동작이 제 편집에 의해 변경되지는 않았지만. 그러나 나는 ^^ 편집을 추측 죄송 것보다 안전한 것이 더 낫다 : * 고정 * – user1555857