gpt4 book ai didi

运行重绘方法后,JAVA swing gui 窗口会出现抖动

转载 作者:行者123 更新时间:2023-12-02 02:00:27 27 4
gpt4 key购买 nike

我开始学习Java Swing。我试图创建一个 GUI,其中有 2 个按钮,底部的 changeColor 和右侧的 changeLabel 。它的右侧有一个标签,中间有一个 JPanel,显示一个渐变色的椭圆形。

当我单击changeLabel时,它工作正常并更改左侧的标签。但是,当我单击 changeColor 时,会出现一个新的椭圆形,并且整个布局会中断,并叠加一些新面板。我正在关注一本书,其中给出了相同的内容,但它在 paintComponent 方法中使用随机颜色生成,这是我从这里学到的,这不是一件好事。该方法效果很好,但我试图避免这种情况并制定一个单独的方法。但这不起作用。

GUI 类:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TwoButtons {
public JFrame frame;
private JLabel label;
private MyDrawPanel panel;
private boolean clicked = false;

public static void main(String[] args) {
TwoButtons gui = new TwoButtons();
gui.go();
}

public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("Change Label");
labelButton.addActionListener(new LabelListener());

JButton colorButton = new JButton("Change color");
colorButton.addActionListener(new ColorListener());

label = new JLabel("I'm a label");
panel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);

frame.setSize(300, 300);
frame.setVisible(true);
}

class LabelListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (!clicked) {
label.setText("Ouch!! (Click again to revert)");
clicked = true;
} else {
clicked = false;
label.setText("Change Label");
}
}
}

class ColorListener implements ActionListener {
@Override//
public void actionPerformed(ActionEvent e) {
//frame.repaint();
panel.changeColors();
}
}
}

着色类:

import javax.swing.*;
import java.awt.*;

public class MyDrawPanel extends JPanel{
private Color startColor,endColor;
public MyDrawPanel(){
this.changeColors();
}
public void paintComponent(Graphics g){
Graphics2D g2D=(Graphics2D)g;
GradientPaint gradient=new GradientPaint(70,70,startColor,150,150,endColor);
g2D.setPaint(gradient);
g2D.fillOval(70,70,100,100);
}
public void changeColors(){
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
endColor = new Color(red, green, blue);
this.repaint();

}

}

点击更改颜色之前

Original gui

点击更改颜色后

After clicking on change color

最佳答案

为了避免渲染伪影:

public void paintComponent(Graphics g){ .. 

应该是:

public void paintComponent(Graphics g){ 
super.paintComponent(g); ..

通过调用super方法,会自动重新绘制背景、边框等,从而删除之前的绘制。

关于运行重绘方法后,JAVA swing gui 窗口会出现抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51655954/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com