gpt4 book ai didi

java - 单击时创建的 JPanel 未出现

转载 作者:行者123 更新时间:2023-12-01 12:37:41 25 4
gpt4 key购买 nike

下面的代码不是我的实际代码,而是我想要实现的目标的简洁、可运行的重制版。我希望当用户单击 JPanel hasAnImage 中的图像时,显示 JPanel CP(clickPanel 的一个实例)。我可以在 Netbeans 控制台中看到由于 Sys.out.print 正在执行,但屏幕上没有显示任何内容。我尝试将visible设置为false,然后再次设置为true,并在mousePressed事件中设置revalidate();图像向左移动,但屏幕上没有显示任何内容。目标是让 CP 出现。我缺少什么?希望我的问题很清楚。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Testo extends JFrame{

public Testo(){

BufferedImage image = null;
try {
image = ImageIO.read(new File("C:\\Users\\someimage.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
;
final JLabel label = new JLabel(new ImageIcon(image));
JPanel hasAnImage = new JPanel();
hasAnImage.addMouseListener(new MouseAdapter(){
@Override //I override only one method for presentation
public void mousePressed(MouseEvent e) {
clickPanel CP = new clickPanel();
hasAnImage.add(CP);
revalidate();
//setVisible(false);
//setVisible(true);
}
});
hasAnImage.add(label);
add(hasAnImage);
setVisible(true);
}

public static void main(String[] args) {

Testo frame = new Testo();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class clickPanel extends JPanel{

public clickPanel() {
setPreferredSize(new Dimension(100,60));
setMaximumSize(new Dimension(100,60));
setBackground(new Color(1.0f,1.0f,1.0f,0.1f));
setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.GREEN));
System.out.println("This is being executed...");
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Arial", Font.PLAIN, 12));
g.setColor(Color.GREEN);
g.drawString("CLICK", 2, 2);
}
}
}

最佳答案

除了revalidate(); Pane 之外,您还需要repaint();它。因此你的 mousePressed 方法应该变成:

public void mousePressed(MouseEvent e) {
clickPanel CP = new clickPanel();
hasAnImage.add(CP);
revalidate();
repaint();
}

进一步阅读:http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#repaint()

关于java - 单击时创建的 JPanel 未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25437925/

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