我正在尝试在gridlayout的右侧添加一个数字。问题是这个数字被视为网格的一部分。我希望它在同一帧中分别显示在网格的右侧。我试图制作一个不同的容器,但它没有用。感谢
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Canvas extends JFrame{
public Canvas(){
super("Canvas to draw");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700,700);
Container pane = getContentPane();
pane.setLayout(new GridLayout(10,10));
for (int i = 0; i < 100; i++) {
JButton button = new JButton(Integer.toString(i + 1));
pane.add(button);
}
FigurePane f = new FigurePane();
pane.add(f);
}
}
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class FigurePane extends JPanel{
public void paintComponent(Graphics comp){
Graphics2D comp2D =(Graphics2D)comp;
GradientPaint p1=new GradientPaint(2F,2F,Color.red,335F,335F,Color.blue);
comp2D.setPaint(p1);
comp2D.fillRect(2, 2, 335, 350);
}
}
public class Main {
public static void main(String[] args) {
Canvas c = new Canvas();
c.setVisible(true);
}
}
答案 0 :(得分:1)
将嵌套面板与适当的布局管理器一起使用。例如:
JPanel grid = new JPanel( new GridLayout() );
FigurePanel figure = new FigurePanel();
JPanel main = new JPanel( new BorderLayout() );
main.add(grid, BorderLayout.CENTER);
main.add(figure, BorderLayout.LINE_END);
add(main, BorderLayout.CENTER);
另外,请不要将您的班级称为“画布”。有一个带有该名称的AWT组件,因此会令人困惑。使用更具描述性的名称。