I just started to learn Graphics in Java.
can someone explain that what is different between super() and JFrame?
when I used super() I can draw Graphics, but I can't draw in JFrame.
public class Screen extends JFrame {
public JFrame fra = new JFrame();
private static final long serialVersionUID = 1L;
BufferedImage img=null;
public void paint(Graphics g){
try{
img=ImageIO.read(new File("D:/strawberry.jpg"));
}catch (IOException e){}
try{
g.drawImage(img, 100,100, null);
}catch (Exception e){}
}
public Screen()
{
/*
super ("kingdom");
setSize(700,700);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
*/
// normal JFrame--------------------------------------------------
fra.setTitle("kingdom");
fra.setSize(600,600);
fra.setResizable(false);
fra.setDefaultCloseOperation(EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu option = new JMenu("Option");
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem controlkey = new JMenuItem("Control key");
JMenuItem sound = new JMenuItem("Sound");
fra.setJMenuBar(bar);
bar.add(file);
bar.add(edit);
bar.add(option);
file.add(open);
file.add(save);
file.add(exit);
edit.add(controlkey);
edit.add(sound);
fra.setVisible(true);
//-------------------------------------------------------------
}
public static void main(String[] a){
new Screen();
}
}
Do the drawing in a class that extends JPanel, then set an instance of that class as the content pane of the frame, or add it to the content pane whatever suits you. You can also do this with a class that extends a bare JComponent of course.
The drawing in that class would be done in an override of paintComponent.
Related
I'm a newbie for java and learning for past two months from a book. I've tried a JApplet Menu program from the book.
MenuDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MenuDemo implements ActionListener {
JLabel jlab;
MenuDemo() {
JFrame jfrm = new JFrame("Menu Demo");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 200);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlab = new JLabel();
JMenuBar jmb = new JMenuBar();
JMenu jmFile = new JMenu("File");
JMenuItem jmiOpen = new JMenuItem("Open");
JMenuItem jmiClose = new JMenuItem("Close");
JMenuItem jmiSave = new JMenuItem("Save");
JMenuItem jmiExit = new JMenuItem("Exit");
jmFile.add(jmiOpen);
jmFile.add(jmiClose);
jmFile.add(jmiSave);
jmFile.addSeparator();
jmFile.add(jmiExit);
jmb.add(jmFile);
JMenu jmOptions = new JMenu("Options");
JMenu jmColors = new JMenu("Colors");
JMenuItem jmiRed = new JMenuItem("Red");
JMenuItem jmiGreen = new JMenuItem("Green");
JMenuItem jmiBlue = new JMenuItem("Blue");
jmColors.add(jmiRed);
jmColors.add(jmiGreen);
jmColors.add(jmiBlue);
jmOptions.add(jmColors);
JMenu jmPriority = new JMenu("Priority");
JMenuItem jmiHigh = new JMenuItem("High");
JMenuItem jmiLow = new JMenuItem("Low");
jmPriority.add(jmiHigh);
jmPriority.add(jmiLow);
jmOptions.add(jmPriority);
JMenuItem jmiReset = new JMenuItem("Reset");
jmOptions.addSeparator();
jmOptions.add(jmiReset);
jmb.add(jmOptions);
JMenu jmHelp = new JMenu("Help");
JMenuItem jmiAbout = new JMenuItem("About");
jmHelp.add(jmiAbout);
jmb.add(jmHelp);
jmiOpen.addActionListener(this);
jmiClose.addActionListener(this);
jmiSave.addActionListener(this);
jmiExit.addActionListener(this);
jmiRed.addActionListener(this);
jmiGreen.addActionListener(this);
jmiBlue.addActionListener(this);
jmiHigh.addActionListener(this);
jmiLow.addActionListener(this);
jmiReset.addActionListener(this);
jmiAbout.addActionListener(this);
jfrm.add(jlab);
jfrm.setJMenuBar(jmb);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String comStr = ae.getActionCommand();
if (comStr.equals("Exit"))
System.exit(0);
jlab.setText(comStr + " Selected");
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MenuDemo();
}
});
}
}
But it gives the below exception.
load: MenuDemo is not public or has no public constructor.
java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a
member of class MenuDemo with modifiers ""
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.Class.newInstance(Class.java:436)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:799)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:728)
at sun.applet.AppletPanel.run(AppletPanel.java:378)
at java.lang.Thread.run(Thread.java:745)
So I changed first three lines from class as below:
public class MenuDemo extends JApplet implements ActionListener {
JLabel jlab;
public void MenuDemo() {
Now the applet window is visible but without menus. As a newbie how can I resolve it.
Thank you.
A constructor does not have a return type. Remove void from the following line.
EDIT
Class definition:
public class MenuDemo extends JApplet implements ActionListener {
Change public MenuDemo() to public void init()
Create two functions in your class as follows.
public void start(){}
public void stop(){}
change
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to
jfrm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
My Main class extends JFrame and for some reason, I can't get my MenuBar and items to show correctly. Is there a special way of adding the menubar?
public class Main extends JFrame
{
// DRIVER
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private JMenuBar menuBar;
private JMenu menu,
menuFile;
private JMenuItem menuItemNew,
menuItemExit;
...
// CONSTRUCTOR
public Main()
{
initializeWindow();
initializeMenu();
}
private void initializeWindow()
{
setTitle(TITLE + " " + VERSION);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setBackground(Color.DARK_GRAY);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backgroundColor = new GradientBackground(WINDOW_WIDTH, WINDOW_HEIGHT);
}
private void initializeMenu()
{
// Menubar
menuBar = new JMenuBar();
menuBar.setBounds(0, 0, WINDOW_WIDTH, 72);
menuBar.setBackground(Color.LIGHT_GRAY);
menuBar.setVisible(true);
setJMenuBar(menuBar);
// Menu title
menu = new JMenu();
menu.setForeground(Color.BLACK);
menuBar.add(menu);
// File Option
menuFile = new JMenu("FILE");
menuFile.setForeground(Color.BLACK);
menuFile.setBackground(Color.DARK_GRAY);
menuBar.add(menuFile);
// New File
menuItemNew = new JMenuItem("New");
menuItemNew.setForeground(Color.BLACK);
menuItemNew.setBackground(Color.DARK_GRAY);
menuFile.add(menuItemNew);
// New File
menuItemExit = new JMenuItem("Exit");
menuItemExit.setForeground(Color.BLACK);
menuItemExit.setBackground(Color.DARK_GRAY);
menuItemExit.setEnabled(true);
menuFile.add(menuItemExit);
getContentPane().add(menuBar);
} // END initializeMenu()
I think that you looking for JFrame.setMenuBar instead of add(JMenuBar)
there no required getContentPane() for Java 5 and newer version
don't to extend JFrame, create this Object as local variable
anyone can tell why the class OpenMenuListener doesnt send a feedback when i click the open button in my Gui ? The erase button works though. It sends me a feedback. I'm exausted.
import java.awt.*;
import javax.swing.*;
public class DrawingApplication extends JFrame {
JComponent drawingArea;
class EraseButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked erase");
}
}
class OpenMenuListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked open");
}
}
public DrawingApplication() {
JPanel frame = new JPanel();
add(frame);
// panel1.add( new JButton(Figuur),BorderLayout.CENTER);
drawingArea = new JLabel();
// label1.add(drawingArea);
frame.add(drawingArea);
// Creates a menubar for a JFrame
JMenuBar menuBar = new JMenuBar();
// Add the menubar to the frame
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenu open = new JMenu("Open");
fileMenu.add(open);
fileMenu.addSeparator();
JMenu save = new JMenu("Save");
fileMenu.add(save);
fileMenu.addSeparator();
JMenu close =new JMenu("Close");
fileMenu.add(close);
JMenu helpMenu = new JMenu("Help");
menuBar.add(helpMenu);
helpMenu.add(new JMenu("Info"));
JPanel panel2 = new JPanel();
add(BorderLayout.SOUTH, frame);
frame.add(new JLabel("figuurkeuze"));
frame.add(panel2);
setVisible(true);
JRadioButton rectButton = new JRadioButton("Rectangle");
JRadioButton triangleButton = new JRadioButton("Triangle");
JRadioButton circleButton = new JRadioButton("Circle");
frame.add(rectButton);
frame.add(triangleButton);
frame.add(circleButton);
JButton erase = new JButton("Erase");
frame.add(erase);
EraseButtonListener eraselistener = new EraseButtonListener();
erase.addActionListener(eraselistener);
OpenMenuListener openMenuListener = new OpenMenuListener();
open.addActionListener(openMenuListener);
}
public static void main(String[] args) {
DrawingApplication frame = new DrawingApplication();
frame.setTitle("My prgram");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
It seems a problem of name aliasing, you add the listener to the open variable which is declared as a JMenuItem, so you are adding the ActionListener to the menu item instead that to a button (that you never declare since there is no JButton open = new JButton("open") anywhere).
I had a simple drawing application. I need to add a menu and a toolbar on the left side.
So now, instead of using a simple JFrame, I'm creating a simple class that extends JFrame. I was able to add the menu following some examples online, but can't figure out how to add a JToolBar. I've tried a few different ways, but nothing works. I don't get an error, everything complies just fine, but I don't see any JToolBar.
Here's the code for my JFrame, I hope you can help.
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton newb = new JButton("new");
toolbar.add(newb);
// toolbar.setOpaque(true);
toolbar.setLocation(100, 100);
toolbar.setVisible(true);
// toolbar.setMinimumSize(new Dimension(100, 100));
// toolbar.setAlignmentX(0);
// panel.add(toolbar);
add(toolbar, BorderLayout.NORTH);
getContentPane().add(toolbar, BorderLayout.NORTH);
// getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
setTitle(title);
pack();
setLocationRelativeTo(null); // Center window.
}
// OpenAction
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
its work fine, and you don't need to setVisible tool bar because its showing by default, also don't add the tool bar two time in the same place (NORTH)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuDemo {
public static void main(String... args) {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
JFrame menu = new Menu("Testing");
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setVisible(true);
}
}
);
}
}
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
JButton newb = new JButton("new");
toolbar.add(newb);
add(toolbar, BorderLayout.NORTH);
setTitle(title);
setLocationRelativeTo(null);
pack();
}
// OpenAction
private class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
My problem was that I was the way I was instantiating my JFrame. I was using a helper function like this one:
public static JFrame openInJFrame(Container content, int width, int height,
String title, Color bgColor) {
// ...
frame.setContentPane(content);
frame.setVisible(true);
return (frame);
}
So my JToolBar was getting replaced by the Container object...
Thanks guys! Your answers helped me figure out my problem.
Whenever I add a background (Image img) to my JFrame I am unable to see my menu bar .... Any help would be greatly appreciated ... I'm just learning JFrames and am probably overlooking something stupid.
class GameFrame extends JFrame {
private JLabel statusbar;
Image img = new ImageIcon("splash.png").getImage();
public GameFrame() {
initUI();
menuUI();
BackgroundLoader bg = new BackgroundLoader();
}
#Override
public void paint(Graphics g) {
try {
Image img = ImageIO.read(new File("splash.png"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
public final void initUI() {
setTitle("Super RPG Hero: The Quest for Fame and Fortune");
setSize(800, 480);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//JLabel background = new JLabel(splash);
//background.setBounds(0, 0, splash.getIconWidth(), splash.getIconHeight());
//getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
}
public final void menuUI() {
JMenuBar menubar = new JMenuBar();
//Creates file menu item
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
//Creates Object for New Game toolbar
JMenuItem newItem = new JMenuItem("New Game");
newItem.setMnemonic(KeyEvent.VK_C);
newItem.setToolTipText("New Game");
newItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String playerName = "Peter";
CharacterCreator characterOne = new CharacterCreator(playerName);
characterOne.statBuilder();
}
});
//Creates Object for Save Game toolbar
JMenuItem saveItem = new JMenuItem("Save");
saveItem.setMnemonic(KeyEvent.VK_C);
saveItem.setToolTipText("Save Game");
//Creates Object for Load Game toolbar
JMenuItem loadItem = new JMenuItem("Load");
loadItem.setMnemonic(KeyEvent.VK_C);
loadItem.setToolTipText("Load Game");
//Creates Object for Exit Game toolbar
//And creates method for the game to exit
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic(KeyEvent.VK_C);
exitItem.setToolTipText("Exit Game");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
//Adds created objects to GUI
file.add(newItem);
file.add(saveItem);
file.add(loadItem);
file.add(exitItem);
menubar.add(file);
setJMenuBar(menubar);
}
}
You should implement paintComponent() and not paint().
By overriding paint and not delegating up, you're not letting the JFrame paint what it needs to paint.
Also, look at this answer.