Help with drawing custom graphics in Swing
I know that i am not calling the graphics paint command in the mainframe in order to display it. but i'm not sure how开发者_高级运维. thanks in advance
import java.awt.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static Panel panel = new Panel();
public MainFrame() {
panel.setBackground(Color.white);
Container c = getContentPane();
c.add(panel);
}
public void paint(Graphics g) {
g.drawString("abc", 20, 20);
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Read the section from the Swing tutorial on Custom Painting for working examples on painting as well as other Swing basics.
Also, don't use Panel, that is an AWT class. Use JPanel which is a Swing class.
Create a new class that extends JComponent override the public void paintComponent(Graphics g) method and draw your string.
Add this overridded component to your frame. Like: frame.getContentPane().add(customComponent);
First of all, you need to create your AWT / Swing stuff in the Event Dispatch Thread. Second of all, you shouldn't be overriding paint on the main window. You need to create a subclass of Component
and override the paintComponent(Graphics g)
method, putting in there whatever you have in paint
at the moment. After this, add the component to the frame. You might need to mess with layout managers depending on your needs.
You can create a class that extends JPanel like this:
public class MyPanel extends JPanel{
public MyPanel(){
setBackground(Color.WHITE);
}
public void paintComponent(Graphics g) {
g.drawString("abc", 20, 20);
}
}
Then you can add that panel to your JFrame.
public class MainFrame extends JFrame {
private JPanel panel;
public MainFrame() {
panel = new MyPanel();
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setSize(600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
精彩评论