我需要学习如何创建自己的Painter方法的JPanel
颜色。我为示例创建一个示例项目;绘制用自己的Painter创建的JPanel
问题:按钮操作中的直接颜色更改代码不会改变任何内容。
问题1)是覆盖paintComponent
方法是有道油漆他JPanel
与Gradient
颜色,同时面板创造?
问题2)如何将此JPanel
的背景颜色与其他Gradient
颜色或Direct
颜色更改为背景颜色?
--CODE--
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);'。 – VGR
*“问题1)覆盖paintComponent方法是否适合使用面板创建时使用渐变颜色绘制JPanel?” - 是的;但请参阅VGR评论; *“问题2)如何用其他渐变颜色或直接颜色更改此JPanel的背景颜色?” - 使用实例字段来存储当前值,使用setter来更改它们,getter来检索它们,调用'repaint'在组件上安排重新绘制。 – MadProgrammer
避免使用'null'布局,像素完美的布局是现代UI设计中的幻想。影响组件的个体大小的因素太多,其中没有一个可以控制。 Swing旨在与布局经理一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来尝试纠正 – MadProgrammer