- 您好我有以下类,我想在我的JFrame中显示内容(paintComponentor,该面板与paint类中的这个矩形) . 我试着通过查看本论坛上发布的不同示例来了解如何实现这一点但是这对我没有帮助我需要一个简单的例子,如面板内部的框架与油漆组件或类似的东西,以了解应该如何工作! PS . 不要把我挂在树上因为我是新手jut问问题!!!
[我想要这样的东西] [1]
package scp;
import java.awt.*;
import javax.swing.*;
public class Panel extends JPanel {
public Panel() {
//this.setPreferredSize(new Dimension(200,200));
//panel = new Panel();
setVisible(true);
setLayout(new FlowLayout());
setSize(200, 300);
getRootPane();
}
@Override
public void paintComponent(Graphics g){
g.drawString("HEY",20,20);
g.drawRect(200, 200, 200, 200);
}
}
and
package scp;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.beans.EventHandler;
public class Frame extends JFrame {
JButton redButton;
JButton blueButton;
public Frame()
{
super("EventHandling");
setLayout(new FlowLayout());
redButton = new JButton("Red");
add(redButton);
blueButton = new JButton("Blue");
add(blueButton);
EventHandler h = new EventHandler();
redButton.addActionListener(h);
blueButton.addActionListener(h);
}
private class EventHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==redButton)
getContentPane().setBackground(Color.RED);
else if(e.getSource()==blueButton)
getContentPane().setBackground(Color.BLUE);
}
}
}
and
package scp;
import javax.swing.JFrame;
public class EventHandling {
public static void main(String[] args) {
Frame f = new Frame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
f.setVisible(true);
f.getContentPane().add(new Panel());
}
}
1 回答
首先来看看:
Painting in AWT and Swing
Performing Custom Painting
2D Graphics
这可能是我能做到的最简单的......
Compound Example
此示例使用
outer
面板,该面板上应用了空边框,这会推动outer
面板边缘的内容 .内部面板(与上一个示例相同),作为应用于它的浅灰色边框,以便您可以看到它,红色矩形仍然由面板
paintComponent
方法绘制 .