JButton 未显示在屏幕上
JButton not shown on screen
我正在尝试制作一个应用程序,只需单击一个按钮即可更改交通灯的状态。
我的代码:Main
import javax.swing.*;
public class PP416
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Traffic light");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TrafficPanel());
frame.pack();
frame.setVisible(true);
}
}
JPanel Class:
import javax.swing.*;
import java.awt.*;
import java.awt.Event;
public class TrafficPanel extends JPanel
{
private JButton button;
private int indicator = 0; // Light is off
public TrafficPanel()
{
button = new JButton("Change");
this.add(button);
}
public void paint(Graphics g)
{
if (indicator == 0)
{
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}
}
按钮只是没有出现,只有椭圆形。
谁能帮我解决这个问题?
不要覆盖 paint
而是 paintComponent
和 最重要的 ,调用 super 的方法。您缺少 super 调用可能会阻止您的 JPanel 很好地绘制其子组件。
例如,
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (indicator == 0) {
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}
我正在尝试制作一个应用程序,只需单击一个按钮即可更改交通灯的状态。 我的代码:Main
import javax.swing.*;
public class PP416
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Traffic light");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TrafficPanel());
frame.pack();
frame.setVisible(true);
}
}
JPanel Class:
import javax.swing.*;
import java.awt.*;
import java.awt.Event;
public class TrafficPanel extends JPanel
{
private JButton button;
private int indicator = 0; // Light is off
public TrafficPanel()
{
button = new JButton("Change");
this.add(button);
}
public void paint(Graphics g)
{
if (indicator == 0)
{
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}
}
按钮只是没有出现,只有椭圆形。 谁能帮我解决这个问题?
不要覆盖 paint
而是 paintComponent
和 最重要的 ,调用 super 的方法。您缺少 super 调用可能会阻止您的 JPanel 很好地绘制其子组件。
例如,
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (indicator == 0) {
g.drawOval(30, 40, 30, 30);
g.drawOval(30, 70, 30, 30);
g.drawOval(30, 100, 30, 30);
}
}