有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

油漆(g)中JLabel的java设置文本是否错误?

下面是代码片段:

        int area;
        int[] xcoords = new int[3];
        xcoords[0] = coordsAX;
        xcoords[1] = coordsBX;
        xcoords[2] = coordsCX;
        sortArray(xcoords);
        int[] ycoords = new int[3];
        ycoords[0] = coordsAY;
        ycoords[1] = coordsBY;
        ycoords[2] = coordsCY;
        sortArray(ycoords);
        //Remember, array[0] is the biggest and array[2] is the smallest!
        int rectWidth = xcoords[0] - xcoords[2];
        int rectHeight = ycoords[0] - ycoords[2];

        area = (rectWidth * rectHeight);
        System.out.println(area);
        lblArea.setText("Area: " + area);

整个代码都在我的applet的paint(g)方法中。我的目标是让用户能够看到JLabel。计算结果完全正确。但当我运行时,小程序看起来像:

enter image description here

我认为setText线不应该在paint(g)中,但在这种情况下,它应该放在哪里,以使其在生成新三角形之前(通过单击“Click Me”按钮)JLabel保持不变

请注意,我是一名自学Java的高中生,因此,我的语言知识看起来像一大块瑞士奶酪。我希望您能给出一些解释,不要解释太多远高于基本小程序制作水平的主题。:)

谢谢你的帮助!谢谢


共 (1) 个答案

  1. # 1 楼答案

    大概你有一个动作监听器连接到“点击我”按钮

    当启动操作时,我会在此时更新标签和UI

    你可能想通读一下How to Write an Action Listener

    (我也有点担心,看起来你用的是AWT而不是Swing,但我可能弄错了;)

    更新的示例

    enter image description here

    public class TestArea {
    
        public static void main(String[] args) {
            new TestArea();
        }
    
        public TestArea() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new AreaPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class AreaPane extends JPanel {
    
            private JLabel areaLabel;
    
            public AreaPane() {
                areaLabel = new JLabel("Area: ...");
                JButton clickMe = new JButton("Click Me");
                clickMe.addActionListener(new ActionListener() {
    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        areaLabel.setText("Area: " + NumberFormat.getNumberInstance().format(Math.random() * 1000));
                        // update UI as required
                    }
    
                });
    
                add(areaLabel);
                add(clickMe);
            }
        }
    }