我想在一个Frame中添加2个不同的面板。一个面板在框架中添加了几个按钮。其他框架将棋盘添加到框架中。我很困惑,如何在面板上绘制这块板。我的Frame将在顶部有一块板,在底部有按钮。此外,让我知道如果我在给定的代码中出错了可以有人帮助我吗?我的代码是
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame main;
private JPanel board;
private JPanel buttons;
private JButton add;
private JButton delete;
public Test()
{
main=new JFrame();
board=new JPanel();
buttons=new JPanel();
add=new JButton("Add");
delete=new JButton("Delete");
init();
addButtons();
}
public void init()
{
main.setSize(700,700);
main.setVisible(true);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
}
public void addButtons()
{
buttons.setSize(700,40);
buttons.setLayout(new FlowLayout());
buttons.add(add);
buttons.add(delete);
main.add(buttons,BorderLayout.SOUTH);
}
public void addBoxes()
{
// what should be my code here...??
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test();
}
}
答案 0 :(得分:3)
JPanel
。paintComponent
方法Graphics
上下文查看一些Painting Graphics tutorials
同时,给它一个旋转
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Board extends JPanel {
private static final int DIM_WIDTH = 640;
private static final int DIM_HEIGHT = 640;
private static final int SQ_SIZE = 80;
boolean black = true;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < DIM_HEIGHT; i += SQ_SIZE) {
if (black) {
black = false;
} else {
black = true;
}
for (int j = 0; j < DIM_WIDTH; j += SQ_SIZE) {
if (black) {
g.setColor(Color.WHITE);
g.fillRect(j, i, SQ_SIZE, SQ_SIZE);
black = false;
} else {
g.setColor(Color.BLACK);
g.fillRect(j, i, SQ_SIZE, SQ_SIZE);
black = true;
}
}
}
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new Board());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(DIM_WIDTH, DIM_HEIGHT);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}