简体   繁体   English

在JFrame中刷新JPanels

[英]refreshing JPanels within a JFrame

I have 3 different panels in my JFrame and I am trying to update my 1st and 3rd panel in it each time I call a method which changes the text of the buttons within the panels. 我的JFrame中有3个不同的面板,每当我调用一种更改面板中按钮文本的方法时,我都试图在其中更新第1和第3面板。 (Inside the 3rd panel (panel), there are 49 buttons in a 7 by 7 gridlayout) (在第3个面板(面板)内部,在7 x 7网格布局中有49个按钮)

The first panel (panel1) only has 1 jbutton that I am trying to update the text but it doesn't work either. 第一个面板(panel1)仅具有1个我要更新文本的jbutton,但它也不起作用。

    public void update() {
    for (int c=0; c< Board.COLS; c++) {
        for (int r=0; r< Board.ROWS; r++) {
            JButton b = (JButton) panel.getComponent(r*7+c);
            b.setOpaque(true);
            b.setFocusable(false);
            b.setPreferredSize(new Dimension(220,220));
            b.setFont(b.getFont().deriveFont(Font.BOLD, b.getFont().getSize()*6));

            b.setText("" + board.map[c][r].getType());
            panel.add(b);
            }
        }

    JButton extra = (JButton) (panel1.getComponent(0));
    extra.setPreferredSize(new Dimension(200,100));
    extra.setFont(extra.getFont().deriveFont(Font.BOLD, extra.getFont().getSize()*6));
    extra.setText("" + board.oldTile.getType());
    panel1.add(extra);

    panel.repaint();
    panel1.repaint();
}`

What I have here does some sort of refreshing on my JFrame but its going all over the place. 我在这里拥有的东西在我的JFrame上进行了某种刷新,但它遍地都是。 The values are not where it should be and sometimes the JButtons are empty. 值不在应有的位置,有时JButton为空。 I think the issue is getting the specific button inside a panel, and I don't know how to do that. 我认为问题在于将特定按钮放置在面板内,但我不知道该怎么做。

panel.add(b);

So you keep on adding the same button, though resulting in messing up the component ordering. 因此,您将继续添加相同的按钮,尽管这会导致组件排序混乱。

My opinion would be to keep a JButton[][] two-dimensional array, fill 'er up just after each button creation and addition to parent. 我的意见是保留一个JButton[][]二维数组,在每次创建按钮并将其添加到父项后立即填充。 Access your buttons directly from there via row and column, without the need to keep track of the component count. 通过行和列直接从那里访问您的按钮,而无需跟踪组件数量。

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

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