gpt4 book ai didi

java - 如何为CardLayout中的所有面板设置单一背景?

转载 作者:行者123 更新时间:2023-12-01 18:17:07 24 4
gpt4 key购买 nike

我正在使用 CardLayout 在 Netbeans 中设计一个应用程序& 我想为我的所有 JPanel 使用相同的背景对象。

我已经尝试使用How to add an image to a JPanel?中讨论的方法来完成我想要的事情,但是我还没有弄清楚如何为我的所有面板使用相同的图像。

最佳答案

How to set a single background for all panels in CardLayout..

使它们全部透明。

enter image description here

这张图片是午夜时分的煤矿照片。

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

public class BackgroundImageForCardLayout {

private JComponent ui = null;
private Image image= new BufferedImage(400,300,BufferedImage.TYPE_INT_RGB);

BackgroundImageForCardLayout() {
initUI();
}

public void initUI() {
if (ui!=null) return;

ui = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
};

final CardLayout cl = new CardLayout();
ui.setLayout(cl);

final String[] names = {"Card 1", "Card 2", "Card 3"};
for (String name : names) {
JPanel p = new JPanel(new GridLayout());
p.setOpaque(false);
p.add(getBigColoredLabel(name));
p.setOpaque(false);
ui.add(p, name);
}
ActionListener animationListener = new ActionListener() {

int i=0;

@Override
public void actionPerformed(ActionEvent e) {
String name = names[i%names.length];
cl.show(ui, name);
i++;
}
};
Timer timer = new Timer(750, animationListener);
timer.start();
}

private final JLabel getBigColoredLabel(String text) {
JLabel l = new JLabel(text, SwingConstants.CENTER);
l.setForeground(Color.RED);
Font f = l.getFont();
l.setFont(f.deriveFont(120f));
return l;
}

public JComponent getUI() {
return ui;
}

public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BackgroundImageForCardLayout o =
new BackgroundImageForCardLayout();

JFrame f = new JFrame("Background Image for CardLayout");
// Hack to terminate the Timer on close.
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);

f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());

f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

关于java - 如何为CardLayout中的所有面板设置单一背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911883/

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