在另一个类中添加Component时,JPanel不会更新 [英] JPanel doesn't update when adding Component in another class

查看:183
本文介绍了在另一个类中添加Component时,JPanel不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java Swing的新手,我遇到了一些问题。

I'm fairly new to Java Swing and I'm running into a few problems.


  1. 作为一个附带问题,在制作相当大的Java Swing应用程序时,分割代码的最佳方法是什么?
    在我的情况下,我希望有一个应用程序,其布局就像Microsoft Word一样,其中有一个填充了按钮的JToolBar和一个主要的JPanel,根据工具栏中按下的按钮进行更改。

  2. 因此,如下面的代码所示,我有一个JFrame,我调用MainPanel类来创建一个面板并添加一个带按钮的ToolBar。按下按钮后,它会向面板添加一个按钮。在你调整窗口大小之前单击没有显示的按钮时出现问题(在我的情况下,我只需手动拖动屏幕使其变大)。

  1. As a side question, when making a fairly large Java Swing Application, what is the best way to split up code? In my case I want to have an application that has a layout just as Microsoft Word where there is a JToolBar filled with buttons and a main JPanel where changes are made based on the buttons pressed in the Tool Bar.
  2. So as shown in the code below, I have a JFrame and I call the MainPanel class in order to create a panel and add a ToolBar with a button. When the button is pressed it adds a button to the panel. The problem comes when you click the button nothing shows up until you resize the window(in my case I simply manually drag the screen to make it larger).

public class Main {

private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("MathMaker");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create the menu bar.  Make it have a green background.
    //MainToolBar mainTB = new MainToolBar();
    MainPanel mainPanel = new MainPanel();

    frame.getContentPane().add(mainPanel.getGUI(), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}

public class MainPanel implements ActionListener{
JPanel mPanel;
JToolBar mToolBar;
JButton addQuestion;
    public MainPanel() {
        mPanel = new JPanel(new BorderLayout());
        mToolBar = new JToolBar();
        addQuestion = new JButton("test");

}


推荐答案

您应该重新验证您的面板

You should revalidate your panel

@Override
public void actionPerformed(ActionEvent e) {
   JButton temp = new JButton("temp");
   mPanel.add(temp);
   mPanel.revalidate();
   mPanel.repaint();
}

这篇关于在另一个类中添加Component时,JPanel不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆