【问题标题】:Something seems wrong with the layout, JButton showing unexpected behaviour at resize of the window布局似乎有问题,JButton 在调整窗口大小时显示出意外行为
【发布时间】:2012-04-08 15:32:33
【问题描述】:

JRE 版本 1.7 更新 3

预期行为

当我运行程序时,它按预期运行,一切正常。当我单击STOP JButton 时,动画停止并且同一JButton 上的文本更改为START。现在,当我点击BALL COLOURJButton 时,BALL 的颜色会发生变化,BALL COLOUR 的颜色也会发生变化,JBUTTON 的颜色也会变化为BALL 的颜色。如果我按原样运行我的应用程序而不调整大小,则整个行为都有效。

意外行为

但是当我RESIZE 我的JFrame 时,通过拉动Right Side,就会显示我的应用程序的意外行为,也就是说如果我按下STOP JButton 然后点击@987654339 @按钮,之前单击的JButton上的文本更改为START的文本将在不应该更改时再次更改为STOP,以及BALL COLOUR的颜色JButton将保持不变或将转至BLUE,此时应更改为球的颜色。我附上图片以获取更多信息。但是,如果您尝试将其调整回原始大小或更接近原始大小,那么一切都会恢复正常。为什么会这样?任何想法或线索将不胜感激。

当我的应用程序以上述预期行为运行时:

这里是意外行为

底线:

为什么应用程序正常运行,在 BEGINNING 处,但不是在 RESIZED 时通过拖动它是 RIGHT SIDE,但是如果你将它带到它的原始大小或更接近它,​​事情就会发生恢复正常,按预期工作?

所以考虑到这种情况,我在程序中做错了什么吗?或者这正是我应该使用SwingWorker 的情况,或者这是Layout 的问题,还是与Content Pane 相关的隐藏问题。请放一些光:-)

这是我正在使用的代码,我已经把它降到最低限度,因为我想证明我的问题:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class BallAnimation
{
    private int x;
    private int y;
    private boolean positiveX;
    private boolean positiveY;
    private boolean isTimerRunning; 
    private int speedValue;
    private int diameter; 
    private DrawingArea drawingArea;    
    private Timer timer;
    private int colourCounter;
     Color[] colours = {
                            Color.BLUE.darker(),
                            Color.MAGENTA.darker(),
                            Color.BLACK.darker(),
                            Color.RED.darker(),
                            Color.PINK.darker(),
                            Color.CYAN.darker(),
                            Color.DARK_GRAY.darker(),
                            Color.YELLOW.darker(),
                            Color.GREEN.darker()
                       };

    private Color backgroundColour;
    private Color foregroundColour; 

    private ActionListener timerAction = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            x = getX();
            y = getY();
            drawingArea.setXYColourValues(x, y, backgroundColour
                                        , foregroundColour);
        }       
    };

    private JPanel buttonPanel;
    private JButton startStopButton;
    private JButton speedIncButton;
    private JButton speedDecButton;
    private JButton resetButton;
    private JButton colourButton;
    private JButton exitButton;

    private ComponentAdapter componentAdapter = new ComponentAdapter()
    {
        public void componentResized(ComponentEvent ce)
        {
            timer.restart();
            startStopButton.setText("STOP");
            isTimerRunning = true;
        }
    };  

    public BallAnimation()
    {
        x = y = 0;
        positiveX = positiveY = true;
        speedValue = 1;
        colourCounter = 0;
        isTimerRunning = false;
        diameter = 50;
        backgroundColour = Color.WHITE.brighter();
        foregroundColour = colours[colourCounter];
        timer = new Timer(10, timerAction);
    }

    private void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("Ball Animation");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        drawingArea = new DrawingArea(x, y
                            , backgroundColour, foregroundColour, diameter);
        drawingArea.addComponentListener(componentAdapter);

        frame.add(makeButtonPanel(), BorderLayout.LINE_END);
        frame.add(drawingArea, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);     
    }

    private JPanel makeButtonPanel()
    {
        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(0, 1));
        buttonPanel.setBorder(BorderFactory.createLineBorder(
                                    Color.DARK_GRAY, 5, true));

        startStopButton = new JButton("START");
        startStopButton.setBackground(Color.GREEN.darker());
        startStopButton.setForeground(Color.WHITE.brighter());
        startStopButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                System.out.println("START/STOP JButton Clicked!");
                if (!isTimerRunning)
                {
                    startStopButton.setText("STOP");
                    timer.start();
                    isTimerRunning = true;
                    buttonPanel.revalidate();
                    buttonPanel.repaint();
                }
                else if (isTimerRunning)
                {
                    startStopButton.setText("START");
                    timer.stop();
                    isTimerRunning = false;
                    buttonPanel.revalidate();
                    buttonPanel.repaint();
                }
            }
        });
        startStopButton.setBorder(BorderFactory.createLineBorder(
                                    Color.WHITE, 4, true));
        buttonPanel.add(startStopButton);

        colourButton = new JButton("BALL COLOUR");
        colourButton.setBackground(colours[colourCounter]);
        colourButton.setForeground(Color.WHITE);
        colourButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                System.out.println("COLOUR JButton Clicked!");
                //timer.restart();
                colourCounter++;
                if (colourCounter == 9)
                    colourCounter = 0;
                foregroundColour = colours[colourCounter];
                drawingArea.setXYColourValues(x, y, backgroundColour
                                                    , foregroundColour);
                //drawingArea.setForegroundForBall(foregroundColour);
                colourButton.setBackground(foregroundColour);
                colourButton.revalidate();
                colourButton.repaint();
                //timer.start();
            }
        });
        colourButton.setBorder(BorderFactory.createLineBorder(
                                    Color.WHITE, 2, true));
        buttonPanel.add(colourButton);

        exitButton = new JButton("EXIT");
        exitButton.setBackground(Color.RED.darker());
        exitButton.setForeground(Color.WHITE.brighter());
        exitButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                System.out.println("EXIT JButton Clicked!");
                timer.stop();
                System.exit(0);
            }
        });
        exitButton.setBorder(BorderFactory.createLineBorder(
                                    Color.RED.darker().darker(), 4, true));
        buttonPanel.add(exitButton);

        return buttonPanel;
    }

    private int getX()
    {
        if (x < 0)
            positiveX = true;
        else if (x >= drawingArea.getWidth() - diameter)
            positiveX = false;
        return (calculateX());
    }

    private int calculateX()
    {
        if (positiveX)
            return (x += speedValue);
        else
            return (x -= speedValue);
    }

    private int getY()
    {
        if (y < 0)
            positiveY = true;
        else if (y >= drawingArea.getHeight() - diameter)
            positiveY = false;
        return (calculateY());
    }

    private int calculateY()
    {
        if (positiveY)
            return (y += speedValue);
        else 
            return (y -= speedValue);
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                new BallAnimation().createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

class DrawingArea extends JComponent
{
    private int x;
    private int y;
    private int ballDiameter;
    private Color backgroundColor;
    private Color foregroundColor;

    public DrawingArea(int x, int y
                , Color bColor, Color fColor, int dia)
    {
        this.x = x;
        this.y = y;
        ballDiameter = dia;
        backgroundColor = bColor;
        foregroundColor = fColor;
        setBorder(BorderFactory.createLineBorder(
                        Color.DARK_GRAY.darker(), 5, true));
    }

    public void setXYColourValues(int x, int y
                            , Color bColor, Color fColor)
    {
        this.x = x;
        this.y = y;
        backgroundColor = bColor;
        foregroundColor = fColor;
        repaint();
    }

    public Dimension getPreferredSize()
    {
        return (new Dimension(500, 400));
    }

    public void paintComponent(Graphics g)
    {
        g.setColor(backgroundColor);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(foregroundColor);
        g.fillOval(x, y, ballDiameter, ballDiameter);
    }
}

**最新编辑:**

【问题讨论】:

  • 我刚刚意识到,如果您将JFrame 至少最大化一次,那么似乎一切都按预期工作:(
  • 我在这里没有看到问题(即没有最大化第一个),使用带有所示代码的 1.6 JRE(在将第三个参数删除到 createLineBorder! 之后)。您显然正在使用 1.7(鉴于第 3 个参数是在 7 中引入的)。这可能是正在使用的 JRE 中的错误吗?
  • 啊哈,我想这可能是一个错误,我使用的是 1.7 更新 3,以前我不能使用 setLayout(new FlowLayout(FlowLayout.LEFT)); 和 1.7 更新 1,你可能是对的 :-),因为如果我最大化然后一切都好,只是当我通过拖动右侧调整它的大小时,它才会给我这种邪恶的行为。我可能会在其他地方再次对其进行测试,再次感谢您的帮助:-)
  • 我建议 1) 制作转储 JRE 版本的版本 2) 获取测试结果以确认模式。 3) 检查错误数据库是否有重复项。 4) 如果没有找到,请提交一个新的。 (当然,您可能会跳到第 3 步并返回到第 1 步和第 2 步。)
  • 如果我将整个窗口最大化一次,那么就不会出现问题:-),只有当我通过拖动右侧来调整它的大小时,事情才会变得混乱:(

标签: java swing resize jframe jbutton


【解决方案1】:

您非常好的示例的问题可能与平台有关,但我可以提供一些意见:

  • 您没有添加或删除组件,因此您不需要revalidate()

  • 因为背景色是按钮的绑定属性,所以不需要后续调用repaint()

  • 确实在您的自定义DrawingArea 中需要repaint(),但您可能希望按照here 的建议尝试添加属性更改支持。

    李>
  • Color.white 不能是brighter()Color.black 不能是darker()Color.darkGray.darker()Color.black()

  • 以下变体使用Queue&lt;Color&gt; 来简化颜色更改。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

/** @see https://stackoverflow.com/q/9849950/230513 */
public class BallAnimation {

    private int x;
    private int y;
    private boolean positiveX;
    private boolean positiveY;
    private boolean isTimerRunning;
    private int speedValue;
    private int diameter;
    private DrawingArea drawingArea;
    private Timer timer;
    private Queue<Color> clut = new LinkedList<Color>(Arrays.asList(
        Color.BLUE.darker(),
        Color.MAGENTA.darker(),
        Color.BLACK,
        Color.RED.darker(),
        Color.PINK,
        Color.CYAN.darker(),
        Color.DARK_GRAY,
        Color.YELLOW.darker(),
        Color.GREEN.darker()));
    private Color backgroundColour;
    private Color foregroundColour;
    private ActionListener timerAction = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            x = getX();
            y = getY();
            drawingArea.setXYColourValues(x, y, backgroundColour, foregroundColour);
        }
    };
    private JPanel buttonPanel;
    private JButton startStopButton;
    private JButton speedIncButton;
    private JButton speedDecButton;
    private JButton resetButton;
    private JButton colourButton;
    private JButton exitButton;
    private ComponentAdapter componentAdapter = new ComponentAdapter() {

        @Override
        public void componentResized(ComponentEvent ce) {
            timer.restart();
            startStopButton.setText("Stop");
            isTimerRunning = true;
        }
    };

    public BallAnimation() {
        x = y = 0;
        positiveX = positiveY = true;
        speedValue = 1;
        isTimerRunning = false;
        diameter = 50;
        backgroundColour = Color.white;
        foregroundColour = clut.peek();
        timer = new Timer(10, timerAction);
    }

    private void createAndDisplayGUI() {
        JFrame frame = new JFrame("Ball Animation");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        drawingArea = new DrawingArea(x, y, backgroundColour, foregroundColour, diameter);
        drawingArea.addComponentListener(componentAdapter);

        frame.add(makeButtonPanel(), BorderLayout.LINE_END);
        frame.add(drawingArea, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel makeButtonPanel() {
        buttonPanel = new JPanel(new GridLayout(0, 1));
        buttonPanel.setBorder(BorderFactory.createLineBorder(Color.darkGray, 5));

        startStopButton = new JButton("Start");
        startStopButton.setOpaque(true);
        startStopButton.setForeground(Color.white);
        startStopButton.setBackground(Color.green.darker());
        startStopButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (!isTimerRunning) {
                    startStopButton.setText("Stop");
                    timer.start();
                    isTimerRunning = true;
                } else if (isTimerRunning) {
                    startStopButton.setText("Start");
                    timer.stop();
                    isTimerRunning = false;
                }
            }
        });
        startStopButton.setBorder(BorderFactory.createLineBorder(Color.gray, 4));
        buttonPanel.add(startStopButton);

        colourButton = new JButton("Change Color");
        colourButton.setOpaque(true);
        colourButton.setForeground(Color.white);
        colourButton.setBackground(clut.peek());
        colourButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                //timer.restart();
                clut.add(clut.remove());
                foregroundColour = clut.peek();
                drawingArea.setXYColourValues(x, y, backgroundColour, foregroundColour);
                colourButton.setBackground(foregroundColour);
            }
        });
        colourButton.setBorder(BorderFactory.createLineBorder(Color.gray, 4));
        buttonPanel.add(colourButton);

        exitButton = new JButton("Exit");
        exitButton.setBackground(Color.red);
        exitButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                timer.stop();
                System.exit(0);
            }
        });
        exitButton.setBorder(BorderFactory.createLineBorder(Color.red.darker(), 4));
        buttonPanel.add(exitButton);

        return buttonPanel;
    }

    private int getX() {
        if (x < 0) {
            positiveX = true;
        } else if (x >= drawingArea.getWidth() - diameter) {
            positiveX = false;
        }
        return (calculateX());
    }

    private int calculateX() {
        if (positiveX) {
            return (x += speedValue);
        } else {
            return (x -= speedValue);
        }
    }

    private int getY() {
        if (y < 0) {
            positiveY = true;
        } else if (y >= drawingArea.getHeight() - diameter) {
            positiveY = false;
        }
        return (calculateY());
    }

    private int calculateY() {
        if (positiveY) {
            return (y += speedValue);
        } else {
            return (y -= speedValue);
        }
    }

    public static void main(String... args) {
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                new BallAnimation().createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

class DrawingArea extends JComponent {

    private int x;
    private int y;
    private int ballDiameter;
    private Color backgroundColor;
    private Color foregroundColor;

    public DrawingArea(int x, int y, Color bColor, Color fColor, int dia) {
        this.x = x;
        this.y = y;
        ballDiameter = dia;
        backgroundColor = bColor;
        foregroundColor = fColor;
        setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 5));
    }

    public void setXYColourValues(int x, int y, Color bColor, Color fColor) {
        this.x = x;
        this.y = y;
        backgroundColor = bColor;
        foregroundColor = fColor;
        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        return (new Dimension(500, 400));
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(backgroundColor);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(foregroundColor);
        g.fillOval(x, y, ballDiameter, ballDiameter);
    }
}

【讨论】:

  • 这些例子再次很棒,像往常一样:-),实际上我写了那些revalidate()repaint() 的东西来解决问题,尽管它们不在我的实际程序中。虽然我找到了原因,至于是什么导致了这个问题,但我真的不知道如何纠正这个问题,当Timer 的实例处于RUNNING 状态时,问题就出现了。当它停止时,就不会出现问题。我曾尝试在colourButtons actionPerformed(...) 方法中设置timer.stop,但无济于事。哈哈。上帝知道现在该怎么做 :-) 再次为精彩的链接和善意的帮助 +1 :-)
  • 不知道这是不是真正的原因,因为如果没有调整大小,那么事情会按预期工作。可能是平台相关的东西 :-) 将与其他人一起测试它以了解它在其他机器上的性能:-)
  • 抱歉,没有想到。我添加了一个最近的变体以供参考。
  • 我转移到 JRE 版本 6 并且一切正常,尽管如果我删除 JRE 1.7 上每个 JButton 的整个 setBorder(...) 语句,即使这样也无法解决问题。但回到 1.6 时,事情就解决了。所以事情已经解决了,但是如何以及是什么造成的仍然是一个谜 :-) 所以这似乎是 JDK 1.7 update 3 中的一个错误:(
  • 有趣;在 Windows 7 上使用 1.7.0_02,我无法重现该异常。如果它还在你的机器上,你可以把它放在%path%
【解决方案2】:

似乎BorderLayout.LINE_END 的东西有问题,只有当我将buttonPanel 放在LINE_END 上时,我才会得到不希望的结果。我曾尝试只使用一个JButton,而不是三个作为最新措施来整理事物。现在出现的问题如下图所示:

已通过将JButton面板的位置更改为LINE_START或使用JRE version 1.6 update 31进行整理,如下图:

这里是这个例子使用的代码:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class BallAnimation
{
    private int x;
    private int y;
    private boolean positiveX;
    private boolean positiveY;
    private boolean isTimerRunning; 
    private int speedValue;
    private int diameter; 
    private DrawingArea drawingArea;    
    private Timer timer;
    private int colourCounter;
     Color[] colours = {
                            Color.BLUE.darker(),
                            Color.MAGENTA.darker(),
                            Color.BLACK.darker(),
                            Color.RED.darker(),
                            Color.PINK.darker(),
                            Color.CYAN.darker(),
                            Color.DARK_GRAY.darker(),
                            Color.YELLOW.darker(),
                            Color.GREEN.darker()
                       };

    private Color backgroundColour;
    private Color foregroundColour; 

    private ActionListener timerAction = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            x = getX();
            y = getY();
            drawingArea.setXYColourValues(x, y, backgroundColour
                                        , foregroundColour);
        }       
    };

    private JPanel buttonPanel;
    private JButton startStopButton;
    private JButton speedIncButton;
    private JButton speedDecButton;
    private JButton resetButton;
    private JButton colourButton;
    private JButton exitButton;

    private ComponentAdapter componentAdapter = new ComponentAdapter()
    {
        public void componentResized(ComponentEvent ce)
        {
            timer.restart();
        }
    };  

    public BallAnimation()
    {
        x = y = 0;
        positiveX = positiveY = true;
        speedValue = 1;
        colourCounter = 0;
        isTimerRunning = false;
        diameter = 50;
        backgroundColour = Color.WHITE.brighter();
        foregroundColour = colours[colourCounter];
        timer = new Timer(10, timerAction);
    }

    private void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("Ball Animation");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        drawingArea = new DrawingArea(x, y
                            , backgroundColour, foregroundColour, diameter);
        drawingArea.addComponentListener(componentAdapter);

        frame.add(makeButtonPanel(), BorderLayout.LINE_START);
        frame.add(drawingArea, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);     
    }

    private JPanel makeButtonPanel()
    {
        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(0, 1));
        buttonPanel.setBorder(BorderFactory.createLineBorder(
                                    Color.DARK_GRAY, 5, true));

        colourButton = new JButton("BALL COLOUR");
        colourButton.setOpaque(true);
        colourButton.setBackground(colours[colourCounter]);
        colourButton.setForeground(Color.WHITE);
        colourButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                System.out.println("COLOUR JButton Clicked!");
                if (timer.isRunning())
                    timer.stop();
                colourCounter++;
                if (colourCounter == 9)
                    colourCounter = 0;
                foregroundColour = colours[colourCounter];
                drawingArea.setXYColourValues(x, y, backgroundColour
                                                    , foregroundColour);
                colourButton.setBackground(foregroundColour);
                if (!timer.isRunning())
                    timer.start();
            }
        });
        colourButton.setBorder(BorderFactory.createLineBorder(
                                    Color.WHITE, 2, true));
        buttonPanel.add(colourButton);

        return buttonPanel;
    }

    private int getX()
    {
        if (x < 0)
            positiveX = true;
        else if (x >= drawingArea.getWidth() - diameter)
            positiveX = false;
        return (calculateX());
    }

    private int calculateX()
    {
        if (positiveX)
            return (x += speedValue);
        else
            return (x -= speedValue);
    }

    private int getY()
    {
        if (y < 0)
            positiveY = true;
        else if (y >= drawingArea.getHeight() - diameter)
            positiveY = false;
        return (calculateY());
    }

    private int calculateY()
    {
        if (positiveY)
            return (y += speedValue);
        else 
            return (y -= speedValue);
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                new BallAnimation().createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

class DrawingArea extends JComponent
{
    private int x;
    private int y;
    private int ballDiameter;
    private Color backgroundColor;
    private Color foregroundColor;

    public DrawingArea(int x, int y
                , Color bColor, Color fColor, int dia)
    {
        this.x = x;
        this.y = y;
        ballDiameter = dia;
        backgroundColor = bColor;
        foregroundColor = fColor;
        setBorder(BorderFactory.createLineBorder(
                        Color.DARK_GRAY.darker(), 5, true));
    }

    public void setXYColourValues(int x, int y
                            , Color bColor, Color fColor)
    {
        this.x = x;
        this.y = y;
        backgroundColor = bColor;
        foregroundColor = fColor;
        repaint();
    }

    public Dimension getPreferredSize()
    {
        return (new Dimension(500, 400));
    }

    public void paintComponent(Graphics g)
    {
        g.setColor(backgroundColor);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(foregroundColor);
        g.fillOval(x, y, ballDiameter, ballDiameter);
    }
}

【讨论】:

  • 奇怪! BorderLayout.EAST 是否也会出现这种情况(是 LINE_END 的粗略等价物吗?)?
  • 是的,同样的问题,BorderLayout.EAST :(
  • 我现在可能已经提出了错误报告。不能说我对迄今为止看到的任何 1.7 实现都印象深刻。它们看起来很马车。
  • 啊哈,其他人也在谈论同样的问题 :-) HORIZONTAL RESIZE,即使他在 EAST 的组件在调整大小时也丢失了,哈哈
  • 在添加更多组件时,即使 OP 在他/她的评论中,在接受的答案下方,它也从未起作用:-)。
【解决方案3】:

【讨论】:

  • 这是另一个很好的例子(+1),但我很困惑,问题出在哪里,因为绘图部分看起来工作正常。只是JButton 的文字和颜色显示了奇怪的行为,resize!!!
  • 真实的是,这是我第一次接触图形,只是展览,没有再尝试过,确定你在等待真正的建议,碰撞是如何工作的
  • 我刚刚意识到,如果我将JFrame 恢复到原来的大小或更接近原来的大小,那么事情又会恢复正常,这可能是布局的问题吗 :-)
【解决方案4】:

我不确定我是否找到了适合您系统的解决方案,但将代码调整为

colourButton = new JButton( "BALL COLOUR" );
colourButton.setOpaque( true );
colourButton.setBackground( colours[ colourCounter ] );
colourButton.setForeground( Color.WHITE );

适用于我的系统(带有 Java 1.7 的 OS X)。请注意 setOpaque 调用,这是必需的,以便 setBackground 调用具有该方法的 javadoc 中所述的任何效果:

设置此组件的背景颜色。仅当组件不透明时才使用背景颜色

在 OS X 上,如果没有 setOpaque 调用,您的代码甚至在调整大小之前都无法工作

【讨论】:

  • 不,很抱歉,但这件事再次给出了相同的结果,当您通过拖动右侧调整 JFrame 的大小时,colourButton 的颜色保持不变或显示一些异常行为。虽然如果我最大化窗口,那么它工作正常,或者我将窗口带到它的原始大小或更接近那个大小。但是当我调整窗口大小时,再次出现相同的行为:(虽然努力+1。谢谢你在这方面的帮助:-)
  • 试试这个,当程序启动时,拖动JFrame的右侧来改变它的宽度,现在点击colourButton,它的颜色永远不会改变:-(
  • 虽然如果你不调整它的大小或者只是稍微改变它以便球可以移动,那么一切正常,就像往常一样,只是当我尝试进一步调整它的大小时,事情就出错了, :( 那件事困扰着我。这里有一些奇怪的东西在起作用 :( ,我猜对我来说是个坏消息。
  • 不,如果我使用setOpaque 呼叫,它总是在我的电脑上工作。没有这个调用,无论是否调整大小,它都无法正常工作
  • @Robin:+1 想法使用setOpaque() 作为 Aqua 的背景颜色。我有时会求助于这个笨拙的alternative。 Gagandeep Bali:和 Robin 一样,我没有发现任何异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 2012-12-24
  • 1970-01-01
相关资源
最近更新 更多