gpt4 book ai didi

java - 在一个 JPanel 中包含的多个 JPanel 中绘图

转载 作者:行者123 更新时间:2023-11-29 03:13:16 25 4
gpt4 key购买 nike

我有一个扩展 JPanel 的类,其中包含 3 个其他面板。我想画成 3 个面板。这就是我的代码必须是什么样的,我做错了什么?执行后我只有一个空框架。

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Thumbnail extends JPanel {

private JPanel bigPanel;
private JPanel panelOne;
private JPanel panelTwo;
private JPanel panelThree;

public Thumbnail() {

panelOne = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawString("writing something", 10, 10);
g.drawRect(10, 10, 50, 50);
}
};
bigPanel = new JPanel();
bigPanel.add(panelOne);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(bigPanel);
//other codes...
}

public static void main(String[] args) {
JFrame jf = new JFrame();
Thumbnail tb = new Thumbnail();
jf.add(tb);
jf.pack();
jf.setVisible(true);
}
}

最佳答案

panelOne 不向布局管理器提供任何布局信息,这意味着默认情况下,它的首选大小为 0x0

尝试添加类似...

@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}

panelOne...

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Thumbnail extends JPanel {

private JPanel bigPanel;
private JPanel panelOne;
private JPanel panelTwo;
private JPanel panelThree;

public Thumbnail() {

panelOne = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawString("writing something", 10, 10);
g.drawRect(10, 10, 50, 50);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}

};
bigPanel = new JPanel();
bigPanel.add(panelOne);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(bigPanel);
//other codes...
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thumbnail tb = new Thumbnail();
jf.add(tb);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
});
}
}

您可能想看看 Initial ThreadsLaying Out Components Within a Container了解更多详情

关于java - 在一个 JPanel 中包含的多个 JPanel 中绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28078693/

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