To output to a graphical user interface requires a different sort of approach. There is no System.out.println in Swing because the "out" object of the System class is linked directly to the standard console screen. Anyway there are a lot of things you can do.
1. You can create an instance of JOPtionPane by calling one of its many static methods, like JOptionPane.showMessageDialog(null, "Message");
where message is what you would like your JFrame to display.
2. If you would like to print directly to the JPanel or JFrame you need to extend the JPanel or JFrame in your class declaration like,
|
Code:
|
import javax.swing.*;
public class MyFrame extends JFrame {
} |
then you need to override the paint method of either the JPanel or the JFrame.
Here is a code example that will paint the X and Y coordinates of your mouse clicks on the back of a JFrame.
|
Code:
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Intro extends JFrame{
int x = 0, y = 0;
Intro() {
super("Writing on the JFrame");
this.setBounds(100,100,300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
x = me.getX();
y = me.getY();
repaint();
}
});
this.setVisible(true);
}
//here is the overridden paint method.
public void paint(Graphics g) {
super.paint(g);
g.drawString("Click the mouse inside the window.",40,45);
g.drawString("X : " + x,40,60);
g.drawString("Y : " + y,40,75);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Intro();
}
});
}
} |
In reality though you would want to paint inside of a JPanel and hold the JPanel inside of a JFrame, rather than painting straight to the back of a JFrame Object.
Look into JOptionDialogs or extending JFrames or JPanels.