首先,创建一个继承自JPanel的类:MyNewPanel,重写MyNewPanel的paintComponent方法:
protected void paintComponent(Graphics g) { Graphics2D g2d=(Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(new Color(255,255,255,150)); g2d.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 20, 20); //先填充内容再画边框,防止边框被内容挡住 g2d.setColor(Color.white); //标题栏 g2d.setClip(2,2,getWidth(),30); g2d.fillRoundRect(2, 2, getWidth()-2, getHeight()-1, 20, 20); g2d.setClip(null); g2d.setColor(Color.green); //画边框 g2d.setStroke(new BasicStroke(4)); g2d.drawRoundRect(1, 1, getWidth()-3, getHeight()-3, 20, 20); g2d.setFont(new Font("Arial", Font.BOLD, 13)); //标题栏的字 g2d.setColor(Color.DARK_GRAY); g2d.drawString("Swing Test UI", 15, 20); }
以上代码可以创建一个带标题栏的半透明的框架。
在frame中添加三个按钮:最大化、最小化、退出。
1、实现拖拽功能:
在类MyFrame中定义四个变量,分别表示鼠标的横纵坐标和框架的横纵坐标:
int mx,my,jfx,jfy;
功能实现:
contentPane.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { setLocation(jfx+e.getXOnScreen()-mx, jfy+e.getYOnScreen()-my); } }); contentPane.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { mx=e.getXOnScreen(); my=e.getYOnScreen(); jfx=getX(); jfy=getY(); } });
2、实现最大化功能:
button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(getExtendedState()==JFrame.MAXIMIZED_BOTH) { setExtendedState(JFrame.NORMAL); }else { setExtendedState(JFrame.MAXIMIZED_BOTH); } } });
3、实现最小化功能:
button_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setExtendedState(JFrame.ICONIFIED); } });
4、实现退出功能:
btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.exit(0); } });
效果如下: