因此,每当我运行该应用程序时,框架就在那里,但是所有颜色和矩形都没有。我要制作3个不同的菜单,每个菜单都比较难处理,所以我的框架中需要3个面板
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JPanel{
public static void main(String[] args) {
JFrame frame = new JFrame("FrogVibes");
JPanel container = new JPanel();
JPanel mainPanel = new JPanel();
JPanel upgradePanel = new JPanel();
JPanel frogPanel = new JPanel();
JButton button = new JButton();
mainPanel.setSize(400,690);
upgradePanel.setSize(400,690);
frogPanel.setSize(400,690);
mainPanel.setBackground(Color.BLACK);
upgradePanel.setBackground(Color.BLACK);
frogPanel.setBackground(Color.BLACK);
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
container.add(mainPanel);
container.add(upgradePanel);
container.add(frogPanel);
new Application() {
};
frame.setContentPane(new Container());
frame.setSize(1280,700);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void Graphics(Graphics g) {
super.paintComponent(g);
g.drawRect(0,700,400,100);
g.drawRect(0, 600,100,150);
}
}
什么是错误的位置,缺少的语句或什么
答案 0 :(得分:0)
您需要创建Application
类的实例并将其添加到JFrame
:
mport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JPanel{
public static void main(String[] args) {
JFrame frame = new JFrame("FrogVibes");
JPanel application = new Application();
frame.add(application);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0,700,400,100);
g.drawRect(0, 600,100,150);
}
}
此外,该方法必须命名为paintComponent()
,而不是Graphics()
。现在,Swing在绘制窗口时将调用paintComponent()
。
答案 1 :(得分:0)
您只有一个错别字,您需要像container
那样将创建的frame
添加到frame.setContentPane(container);
,而不是添加新的容器。我只是改变颜色,以便您可以看到每个面板:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JPanel{
public static void main(String[] args) {
JFrame frame = new JFrame("FrogVibes");
JPanel container = new JPanel();
JPanel mainPanel = new JPanel();
JPanel upgradePanel = new JPanel();
JPanel frogPanel = new JPanel();
JButton button = new JButton("button!");
mainPanel.setSize(400,200);
upgradePanel.setSize(500,690);
frogPanel.setSize(400,690);
mainPanel.setBackground(Color.RED);
upgradePanel.setBackground(Color.BLACK);
frogPanel.setBackground(Color.BLUE);
upgradePanel.add(button);
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
container.add(mainPanel);
container.add(upgradePanel);
container.add(frogPanel);
new Application() {
};
frame.setContentPane(container);
frame.setSize(1280,700);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void Graphics(Graphics g) {
super.paintComponent(g);
g.drawRect(0,700,400,100);
g.drawRect(0, 600,100,150);
}
}