这与我的上一个问题相同(见here),但我仍然无法让一切正常运作。我现在有实际的GUI显示,但没有显示任何内容,例如我的按钮或您绘制的内容。如果有人可以提供帮助,那将非常感激! 谢谢!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Paint{
public static void main(String[] args){
Win frame = new Win();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class gui extends JComponent{
Image image;
Graphics2D draw;
int x, y, prevX, prevY;
gui(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
prevX = e.getX();
prevY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
x = e.getX();
y = e.getY();
draw.drawLine(prevX, prevY, x, y);
repaint();
prevX = x;
prevY = y;
}
});
}
public void changeColor(Color color)
{
draw.setPaint(color);
repaint();
}
public void clear(){
draw.setPaint(Color.white);
draw.fillRect(0, 0, getSize().width, getSize().height);
draw.setPaint(Color.black);
repaint();
}
public void paintComponent(Graphics g)
{
if(image == null)
{
image = createImage(getSize().width, getSize().height);
draw = (Graphics2D)image.getGraphics();
draw.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
}
class Win extends JFrame implements ActionListener{
JButton red, green, blue, clear;
gui gui = new gui();
Win(){
super("Paint");
setSize(500,500);
Container content=new Container();
content.setLayout(new BorderLayout());
content.add(gui, BorderLayout.CENTER);
content.setVisible(true);
JPanel panel = new JPanel();
content.add(panel, BorderLayout.SOUTH);
panel.setPreferredSize(new Dimension(32, 68));
panel.setMinimumSize(new Dimension(32, 68));
panel.setMaximumSize(new Dimension(32, 68));
red = new JButton("Red");
green = new JButton("Green");
blue = new JButton("Blue");
clear = new JButton("Clear");
red.setPreferredSize(new Dimension(50, 16));
green.setPreferredSize(new Dimension(50,16));
blue.setPreferredSize(new Dimension(50, 16));
panel.add(red);
panel.add(green);
panel.add(blue);
panel.add(clear);
panel.setVisible(true);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
clear.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if( e.getSource()==red){
gui.changeColor(Color.red);
repaint();
}
if( e.getSource()==green){
gui.changeColor(Color.green);
repaint();
}
if( e.getSource()==blue){
gui.changeColor(Color.blue);
repaint();
}
if( e.getSource()==clear){
gui.clear();
}
}
}
答案 0 :(得分:2)
看看那个Win
构造函数。您创建了许多组件,将它们添加到许多面板中,但它们实际上都没有添加到Win
实例中。
由于您可以看到Win
个实例,因此没有任何内容显示
补充说明:
ActionListener
的代码set(xxx)Size
。添加所有组件后使用JFrame#pack
setVisible( true )
,只要将它们添加到已经可见的父组件即可Graphics2D
类中使用gui
字段是完全错误的。您应该覆盖自定义绘制的paintComponent
方法gui
类的名称违反了Java命名约定。这使得代码难以阅读答案 1 :(得分:1)
您似乎没有使用您的gui类 - 添加以下行:
frame.add(new Gui());
将框架设置为可见之后(请注意,您已将类命名为gui,这不是标准的)