【发布时间】:2016-05-10 04:21:16
【问题描述】:
我需要学习如何更改创建自己的 Painter 方法的JPanel 颜色的逻辑。我创建了一个示例项目用于说明;
问题:按钮操作中的直接颜色更改代码不会改变任何内容。
问题 1) 覆盖 paintComponent 方法是否适合在创建面板时使用 JPanel 绘制 Gradient 颜色?
问题 2) 如何将 JPanel 的背景颜色更改为其他 Gradient 颜色或 Direct 颜色?
--代码--
package tryingproject2;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TryingProject2 {
public static void main(String[] args) {
class ImagePanel extends JPanel{
public void paintComponent( Graphics g ) {
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
Color color1;
Color color2;
color1 = new Color(223,130,24,255);
color2 = new Color(255,255,255,255);
GradientPaint gp = new GradientPaint(0, 0, color1, w, 0, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel userPanel = new ImagePanel();
userPanel.setBounds(100, 40, 200, 200);
userPanel.setLayout(null);
JLabel newLabel = new JLabel("Sample Label");
newLabel.setBounds(50, 10, 100, 100);
userPanel.add(newLabel);
JButton button = new JButton("Change Color To Red");
button.setBounds(100, 300, 200, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userPanel.setBackground(Color.red);
userPanel.repaint();
System.out.println("Button Pressed.");
}
});
frame.add(userPanel);
frame.add(button);
frame.setVisible(true);
}
}
【问题讨论】:
-
当你重写paintComponent时,你的方法必须做的第一件事就是调用
super.paintComponent(g);。 -
"问题 1) 是否覆盖paintComponent 方法是在面板创建时使用渐变颜色绘制JPanel 的正确方法? - 是的;但见 VGR 评论; *"问题 2) 如何用其他渐变颜色或直接颜色更改此 JPanel 的背景颜色? - 使用实例字段存储当前值,使用 setter 更改它们并使用 getter 检索它们,调用
repaint在组件上安排重绘。 -
避免使用
null布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正
标签: java swing awt paint gradient