设计思路是一个大的Jpanel(继承Frame)上布局有一些常规控件,另外还添加了一个小Jpanel,这个Jpanel上用于绘制出点(点坐标已有)。效果是点击某一个按钮,小Jpanel上绘制出点。问题是运行后Frame下的组件都能显示,但点击按钮小Jpanel绘出的点一闪即逝,或是根本不显示。试过将绘制方法重写并放入另一线程中,仍然不能解决。 急!!!望大神们不吝赐教,谢谢
Java 控件
------解决方案--------------------
和你实现的没啥不一样 ,加了按钮进行测试
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
class MyJPanle extends JPanel
{
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(JPanelTest.flag)
{
//话一个区域
g.setColor(Color.YELLOW);
g.fillRect(20,20,50,80);
//画一行文字
g.setColor(Color.BLACK);
g.setFont(new Font("Times New Roman",Font.BOLD,20));
g.drawString("The National GeoGraphics",40,50);
}
else
{
//话一个区域
g.setColor(Color.YELLOW);
g.fillRect(20,20,50,80);
//画一行文字
g.setColor(Color.BLACK);
g.setFont(new Font("宋体",Font.BOLD,20));
g.drawString("国家地理杂志",40,50);
}
}
}
public class JPanelTest extends JFrame
{
public static boolean flag;
private JPanel big;
private JPanel small;
private JButton btnAction;
static{
flag = true;
}
public JPanelTest()
{
//自由定位
setLayout(null);
setBounds(0,0,800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
big = new JPanel();
big.setBounds(0,0,500,500);
//为了方便看,给Big画一个边框
Border lb = BorderFactory.createLineBorder(Color.ORANGE,7);
big.setBorder(lb);
add(big);
Border lb2 = BorderFactory.createLineBorder(Color.ORANGE,7);
//让小panel 是自己实现的Panel
small = new MyJPanle();
small.setBounds(50,50,300,200);
small.setBorder(lb2);
big.setLayout(null);
big.add(small);
//在samll panel 里面画东西
btnAction = new JButton("Click Me");
btnAction.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JPanelTest.flag = !JPanelTest.flag;
small.repaint();
}
});
btnAction.setBounds(10,10,100,30);
big.add(btnAction);
setVisible(true);
}
public static void main(String[] args)
{
JPanelTest f = new JPanelTest();
System.out.println("Hello World!");
}
}