小编ano*_*mer的帖子

JPanel使用JTextField或JLabel不更新

我试图找到答案,但我很简短.我对java很新.我有4个类(1个主要有一个JFrame和3个JPanels).主类创建JFrame并向其添加3个面板.我想要完成的是从另一个面板(panelB)中的ActionEvent更新1面板(panelA)中的JLabel或JTextField.panelB中的ActionEvent在panelA中运行一个方法,该方法运行setText()方法和repaint()方法.我无法使用新文本更新JLabel或JTextField.

这是我的代码:

App.java

public class App {
    public static void main(String[] args) {
        JFrame nameFrame = new JFrame("Name Form");
        nameFrame.setLayout(new BorderLayout());
        nameFrame.setSize(300,150);
        nameFrame.setLocationRelativeTo(null);
        nameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MiddlePanel middlePanel = new MiddlePanel();
        nameFrame.add(middlePanel, BorderLayout.CENTER);
        BottomPanel bottomPanel = new BottomPanel();
        nameFrame.add(bottomPanel, BorderLayout.SOUTH);
        nameFrame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

BottomPanel.java

import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class BottomPanel extends JPanel {
    private JLabel welcomeLabel = new JLabel("Old Text");

    BottomPanel() {
        super(new FlowLayout());
        add(welcomeLabel);
    }
    public void setText(String text) {
        welcomeLabel.setText(text);
        repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)

MiddlePanel.java

import java.awt.BorderLayout;
import …
Run Code Online (Sandbox Code Playgroud)

java swing constructor jlabel jbutton

4
推荐指数
1
解决办法
3435
查看次数

标签 统计

constructor ×1

java ×1

jbutton ×1

jlabel ×1

swing ×1