简体   繁体   English

难以在JPanel中显示多个JTextField和JLabel

[英]Difficulty displaying several JTextFields and JLabels inside JPanel

I'm having difficulty creating several JTextFields and JLabels in my JPanel for a hangman game I a making. 我很难在我的JPanel中创建几个JTextFields和JLabel,用于我制作的刽子手游戏。 I am trying to display the users input as "Letters Used" in a JLabel. 我试图在JLabel中将用户输入显示为“Letters Used”。 I have commented the area that is not displaying below. 我评论了下面没有显示的区域。 Thanks in advance. 提前致谢。

/*PACKAGE DECLARATION*/
package Game;


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


/************************
 * GAME MECHANICS CLASS *
 * **********************/
public class GameMechanics {


    /* STATIC DECLARATIONS */
    static JPanel jp;//panel
    static JLabel jl;//label
    static JTextField tf;//text field
    static String input = "";


    /*********************
     * USER INPUT METHOD *
     * *******************/
    public void userInput() {

        jp = new JPanel();
        jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
        jl = new JLabel("Enter a Letter");//prompt with label
        tf = new JTextField(null);//length of text field by character
        jp.add(jl);//add label to panel
        jp.add(tf);//add text field to panel


        tf.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            JTextField tf = (JTextField)e.getSource();
            input = tf.getText();//get user input
            JLabel jl2 = new JLabel("Letters Used: " + input);//NOT DISPLAYING
            jp.add(jl2);//NOT DISPLAYING

            }//end actionPerformed method

        });

    }//end userInput method


    /*****************
     * WINDOW METHOD *
     * ***************/
    public void window() {

    LoadImageApp i = new LoadImageApp();//calling image class
    JFrame gameFrame = new JFrame();//declaration
    gameFrame.add(i); //adds background image to window
    i.add(jp); // adds panel containing label to background image panel
    gameFrame.setTitle("Hangman");//title of frame window
    gameFrame.setSize(850, 600);//sets size of frame
    gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
    gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
    gameFrame.setLocationRelativeTo(null);//window centered
    gameFrame.setResizable(false);//user can not resize window
    gameFrame.setVisible(true);//display frame

  }//end window method

}//end GameMechanics class








/*PACKAGE DECLARATION*/
package Game;


/***********************
 * IMPORT DECLARATIONS *
 * *********************/
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;


/***************
 * IMAGE CLASS *
 * *************/
public class LoadImageApp extends JPanel {

    private static final long serialVersionUID = 1L;

        private ImageIcon image;


        /***********************
         * PAINT IMAGE METHOD *
         * *********************/
        public void paintComponent (Graphics g) {

            super.paintComponent(g);
            image = new ImageIcon("hangman.png");//image name & type
            image.paintIcon(this, g, 0, 9);

        }//end paintComponent method

}//end LoadImageApp class










/*PACKAGE DECLARATION*/
package Game;


/*******************
 * GAME MAIN CLASS *
 * *****************/
public class GameMain {


    /***************
     * MAIN METHOD *
     * *************/
    public static void main (String []args) {

        GameMechanics game = new GameMechanics();//declaration
        game.userInput();//userInput call
        game.window();

    }//end main method

}//end GameMain class

There are a number of things about this code that won't work, and a number of things about it that are confusing. 这段代码有很多东西是行不通的,有很多东西让人感到困惑。

The immediate problem is that the panel jp is created in userInput(), and has things added to it there, but it is not itself added to a frame or a window or anything. 直接的问题是面板jp是在userInput()中创建的,并且在那里添加了一些东西,但它本身并没有添加到框架或窗口或任何东西。 So it isn't going to display. 所以它不会显示。

I recommend having all your UI "setup" code in one place -- set up the entire window, with empty labels or text fields or whatever, before the user is expected to enter anything. 我建议将所有UI“设置”代码放在一个地方 - 在用户需要输入任何内容之前,设置整个窗口,使用空标签或文本字段等。 That way, the user doesn't have UI controls "popping up" on him, which is disconcerting since GUIs rarely work that way. 这样,用户没有“弹出”他的UI控件,这是令人不安的,因为GUI很少以这种方式工作。

It is also then easier to make sure that the panels that are to contain your controls are all created, and the layout managers are all set, and the controls are created and placed in the correct panels with the correct layout managers, etc., before you start getting into event-driven logic. 然后,更容易确保创建包含控件的面板,并设置布局管理器,并创建控件并将其放置在具有正确布局管理器等的正确面板中,之后你开始进入事件驱动的逻辑。

One more caution -- any changes made to a Swing UI need to happen on the "event dispatch thread", and if you don't know what that is you need to read a tutorial or two until you figure it out. 还有一点需要注意 - 对Swing UI进行的任何更改都需要在“事件调度线程”上进行,如果你不知道那是什么,你需要阅读一两个教程,直到你弄明白为止。


On the order of code: I find it best to create a container panel, set its layout manager, then create items that will go directly inside that panel and add them. 在代码的顺序:我发现最好创建一个容器面板,设置其布局管理器,然后创建将直接进入该面板并添加它们的项目。 Since nesting panels is common, this can have several layers. 由于嵌套面板很常见,因此可以有多个层。

I'd probably put the controls you're going to have at the top in one panel, and have that panel set to the "north" portion of a borderlayout on the frame. 我可能会将您将要在顶部的控件放在一个面板中,并将该面板设置为框架上borderlayout的“north”部分。 Then I'd create another panel for the center of that borderlayout, and put anything I wanted in the stretchy portion of the frame there. 然后我会为该borderlayout的中心创建另一个面板,并在框架的弹性部分放置我想要的任何东西。 So: create frame, set borderlayout (though actually it's the default), create upper panel, set layout, create upper controls and add them, add that panel to frame in the north, etc. 所以:创建框架,设置borderlayout(虽然实际上它是默认设置),创建上面板,设置布局,创建上部控件并添加它们,将该面板添加到北部的框架等。

I find it best to create and add an action routine along with the other characteristics of that control (label, color, etc.). 我发现最好创建并添加一个动作例程以及该控件的其他特征(标签,颜色等)。 One of the challenges of event-driven code is that, when you write something like an action routine, you must keep in mind that the code is executed in the context of the state of the application when activated; 事件驱动代码的挑战之一是,当你编写类似动作例程的东西时,你必须记住,代码是在激活时在应用程序状态的上下文中执行的; particularly for anonymous inner classes, it requires a bit of a context shift on your part. 特别是对于匿名内部类,它需要你的一些上下文转换。 But the most logical thing for me is to create it with the control. 但对我来说最合乎逻辑的是用控件创建它。

I'm not sure what else you want help with the order of. 我不确定你还想要什么帮助。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM