Я изучаю Java и как сделать GUI с Java.public class Main_Panel extends JPanel {...}
< /code>
В этом классе я создаю основной конструктор и устанавливаю цвет фона на эту панель. < /p>
public Main_Panel() { this.setBackground( MY_COLOR ); }
Если я запускаю, я получаю окно с моим цветом.
< /p>
Теперь я хочу добавить текст. Я видел, что могу сделать это с помощью метода PaintComponent.public Main_Panel() {
this.setBackground( MY_COLOR );
}
public void paintComponent( Graphics g ) {
g.drawString( "Hello, World", 10, 20 );
}
< /code>
Если я сейчас запускаю код, я теряю цвет фона и не понимаю, почему. < /p>
Полный код
1 / - Основной класс < /p>
public class App {
public static void main(String[] args) {
Main_Window mainWindow = new Main_Window( "TEST", 1200, 780 );
}
}
2/ - jframe class
public class Main_Window extends JFrame {
String title;
int x;
int y;
// constructor
public Main_Window( String title, int x, int y ) {
// init
this.title = title;
this.x = x;
this.y = y;
// base
this.setTitle( title );
this.setSize( x, y );
// panes and design
Main_Panel mainPanel = new Main_Panel();
this.setContentPane( mainPanel );
// positions
this.setLocationRelativeTo( null );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setVisible( true );
}
}
3/ - jpanel class
public class Main_Panel extends JPanel {
public static final Color MY_COLOR = Color.decode("#2D2D2D");
public Main_Panel() {
this.setBackground( MY_COLOR );
}
public void paintComponent( Graphics g ){
super.paintComponent(g);
g.drawString( "Hello, World", 10, 20 );
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... background