I am attempting to add components to a JFrame but the only thing being displayed is my ImageIcon when I run GameMenu.java. I have instantiated setVisible(); specifically after I have set my frame or added components to the panels or menubars. So I'm unsure as to why no components are showing up. I think it may have something to do with my formatting or main method.
Here are my two classes:
GameMenu.java:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class GameMenu{
public static void main(String[] args) {
FrameCaller obj = new FrameCaller();
}
}
class FrameCaller extends JFrame {
public FrameCaller(){
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel(new ImageIcon("logo.png")));
pack();
setLocationRelativeTo(null);
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("Game List");
JMenu m2 = new JMenu("Help");
JMenu m3 = new JMenu("Stats");
mb.add(m1);
mb.add(m2);
mb.add(m3);
JMenuItem showRulesButton = new JMenuItem("View game rules");
m2.add(showRulesButton);
JMenuItem m77 = new JMenuItem("View past game stats");
m3.add(m77);
mb.setVisible(true);
JPanel panel = new JPanel();
JButton newGameButton = new JButton("New Game");
newGameButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new inGameFrame();
dispose();
}
});
panel.add(newGameButton);
panel.setVisible(true);
setVisible(true);
}
}
EightOff.java:
import javax.swing.*;
public class EightOff {
public static void main(String[] args)
{
inGameFrame obj = new inGameFrame();
}
}
class inGameFrame extends JFrame
{
public inGameFrame() {
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Any tips would be wonderful. Thanks.
Related
My Java code below is trying to import a photo to place on new JLabel(new ImageIcon("")); using File Chooser. I have no experience with file Chooser but I want to select a image and then have the image place on the jLabel. I don't know what to put in action event e that will help me achieve this goal.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class back extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
public int act = 0;
public back(){
setTitle("Question");
JPanel Panel1 = new JPanel();
Panel1.setLayout(new BorderLayout());
JPanel Panel2 = new JPanel();
Panel2.setLayout(new GridLayout(3,1));
JLabel myButton1 = new JLabel(new ImageIcon(""));
JButton myButton2 = new JButton("2:Select Image");
myButton2.addActionListener(this);
Panel2.add(myButton1);
Panel2.add(myButton2);
Panel1.add(Panel2,BorderLayout.CENTER);
add(Panel1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
SomeImageType image = findImage();
displayImage(image, Panel1);
}
public static void main(String[] args) {
new back();
}
}
I want to have a layout like this:
The grey areas will be two different menus.
I managed to make the split panes, but I can't seem to add the menus, here's my code:
package View;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.plaf.basic.BasicSplitPaneUI;
public class TaskView extends JFrame{
JMenuBar menuBar;
JMenu addTask, refresh;
private int screenHeight,screenWidth;
public TaskView() {
setTitle("TASKS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
Toolkit myScreen = Toolkit.getDefaultToolkit();
Dimension screenSize = myScreen.getScreenSize();
screenHeight = screenSize.height;
screenWidth = screenSize.width;
setSize(screenWidth/2,screenHeight/2);
System.out.println(screenWidth/2);
setLocation(screenWidth/4,screenHeight/4);
placeComponents(this.getContentPane());
}
private void placeComponents(Container contentPane) {
JPanel jsp1 = new JPanel();
JPanel jsp2 = new JPanel();
JLabel j1 = new JLabel("Area 1");
JLabel j2 = new JLabel("Area 2");
menuBar = new JMenuBar();
addTask = new JMenu("Add Task");
refresh = new JMenu("Refresh");
menuBar.add(addTask);
menuBar.add(refresh);
jsp1.add(menuBar);
jsp1.add(j1);
jsp2.add(j2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true, jsp1, jsp2);
splitPane.setUI(new BasicSplitPaneUI());
splitPane.setOneTouchExpandable(false);
contentPane.add(splitPane);
splitPane.setEnabled(false);
setVisible(true);
splitPane.setDividerLocation(300);
}
}
Every time I try to add a menu it makes a mess in the left panel and it dosn't look at all like a menu, how can i add the menus without it looking like shit?
try this
public class TaskView extends JFrame {
public TaskView() throws HeadlessException {
createGUI();
}
private void createGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createPanel(), createPanel());
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JPanel createPanel() {
JPanel panel = new JPanel(new BorderLayout());
JMenuItem menuItem1 = new JMenuItem("MenuItem 1");
JMenuItem menuItem2 = new JMenuItem("MenuItem 2");
JMenuItem menuItem3 = new JMenuItem("MenuItem 3");
JMenu menu = new JMenu("Main");
menu.add(menuItem1);
menu.addSeparator();
menu.add(menuItem2);
menu.add(menuItem3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
menuBar.add(new JMenu("View"));
panel.add(menuBar, BorderLayout.PAGE_START);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TaskView().setVisible(true));
}
}
I m trying to make a main menu with START button, CONTROLS button and HELP button.
I made a backboard for it but I need help with making options.
I tried to make it, but the error says that local variable gameFrame is accessed from within inner class; needs to be declared final
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.System.*;
public class GameFrame {
public static void main(String[] args) {
JFrame gameFrame = new JFrame("PoopMan");
gameFrame.setSize(900, 800);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setResizable(false);
gameFrame.setVisible(true);
gameFrame.getContentPane().setBackground(Color.yellow);
JPanel panel = new JPanel();
JButton button1 = new JButton();
gameFrame.add(panel);
panel.add(button1);
gameFrame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(gameFrame.getComponent(0), "START");
}
});
}
}
I believe you would like to initialize your Game in a non-static context. Do the following.
public class Main {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GameFrame();
}
});
}
}
And
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.System.*;
public class GameFrame extends JFrame {
private void init() {
this.setSize(900, 800);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
this.getContentPane().setBackground(Color.yellow);
JPanel panel = new JPanel();
JButton button1 = new JButton("START");
this.add(panel);
panel.add(button1);
this.setLayout(new FlowLayout());
this.setMinimumSize(new Dimension(300, 300));
this.pack();
this.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(getComponent(0), "START");
}
});
}
public GameFrame() {
super("PoopMan");
init();
}
}
This way, you start the GameFrame on another thread, and you can continue your work within the GameFrame class.
That is quite simple. Please note that this is a place to inquire about issues regarding your code, and not a place to look for answers.
What you should be researching is known as JMenuBar (refer to This Tutorial for Assitance)
Seeing as you are new, I will assist you this once. Below is the code that will accomplish what you ask. (Tried and Tested)
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.System.*;
public class GameFrame
{
static private JMenuBar menuBar;
static private JMenu startMenu, controlsMenu, helpMenu;
static private JMenuItem startBtn;
static private JMenuItem controls;
static private JMenuItem hlpBtn;
public static void main(String[] args)
{
JFrame gameFrame = new JFrame("PoopMan");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.getContentPane().setBackground(Color.yellow);
menuBar = new JMenuBar();
startMenu = new JMenu("File");
controlsMenu = new JMenu("Controls");
helpMenu = new JMenu("Help");
startBtn = new JMenuItem("Start");
controls = new JMenuItem("Controls");
hlpBtn = new JMenuItem("Help");
gameFrame.add(menuBar, BorderLayout.PAGE_START);
menuBar.add(startMenu);
menuBar.add(controlsMenu);
menuBar.add(helpMenu);
startMenu.add(startBtn);
controlsMenu.add(controls);
helpMenu.add(hlpBtn);
gameFrame.pack();
gameFrame.setResizable(false);
gameFrame.setVisible(true);
gameFrame.setSize(900,800);
}
}
I am not certain as to why you are receiving a Final error. It works fine.
From later edits to the question:
JButton button1 = new JButton("Button");
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
gameFrame.add(panel);
panel.add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(gameFrame.getComponent(0), "START");
}
});
I have this GUI setup. tl;dr is: its a gui and a MenuItem calls myActionListener.
There is also an Object o in this class.
I want this object o be accessible by the myActionListener as well as a myActionListener2 etc..
But i cant even call any of the Object methods.
public class MenuDemo implements ActionListener,ItemListener{
// My Object
Object o = new Object();
o.addParam();// wont work
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
menu = new JMenu("A Menu");
menuBar.add(menu);
menuItem = new JMenuItem("Title");
menuItem.addActionListener(new myListener());
menu.add(menuItem);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
Database db = new Database();
final int test = 5;
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
Ive been trying to figure this out for a while but it seems like i cant find any help or maybe im going at it in the wrong way?
As I said in comment, you can pass a reference of the Object to different objects of type/subtype of an ActionListener:
Main class:
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame
{
private JButton btn;
Object o;
public Main()
{
setLayout(new FlowLayout());
o = new String("Hello Beautiful!");
btn = new JButton("Click!");
//Passing the reference `o` to the constructor
btn.addActionListener(new JButtonListener(o));
add(btn);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
new Test1();
}
});
}
}
Class that implements ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class JButtonListener implements ActionListener
{
private Object _obj;
public JButtonListener(Object obj)
{
_obj = obj;
}
#Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, _obj.toString());
}
}
I have a very simple code that creates a frame object from the class MyJFrame accepts the first string which is used as a title. Place the second string is the text to be displayed in a JScrollPane. You can see the code below. What I need is to use copy and paste of text highlighted. I need help implementing it. So that if copy selected from a menubar it copies the highlighted portion and if paste is pastes it.
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
public class DisplayText
{
private static JTextArea text;
public DisplayText(String title, String info)
{
MyJFrame f = new MyJFrame(title);
Container c = f.getContentPane();
//default text
text = new JTextArea(info);
//Scrollpane
JScrollPane sp = new JScrollPane(text);
c.add( sp );
f.setBounds(100,200, 500, 400 );
f.setVisible(true);
}
Use the Actions that are available in the DefaultEditorKit including DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, and DefaultEditorKit.PasteAction.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.text.*;
public class TestActions {
private String[] texts = {
"Hello", "Goodbye", "What the f***?", "Heck if I know", "Peace out man!"
};
private JTextArea textArea = new JTextArea(10, 30);
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
private JPanel mainPanel = new JPanel();
private JMenuBar menubar = new JMenuBar();
private JPopupMenu popup = new JPopupMenu();
private PopupListener popupListener = new PopupListener();
public TestActions() {
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
btnPanel.add(new JButton(textAction));
menu.add(new JMenuItem(textAction));
popup.add(new JMenuItem(textAction));
}
menubar.add(menu);
JPanel textFieldPanel = new JPanel(new GridLayout(0, 1, 5, 5));
for (String text: texts) {
JTextField textField = new JTextField(text, 15);
textField.addMouseListener(popupListener);
textFieldPanel.add(textField);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
((JTextComponent)e.getSource()).selectAll();
}
});
}
textArea.addMouseListener(popupListener);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel textFieldPanelWrapper = new JPanel(new BorderLayout());
textFieldPanelWrapper.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(btnPanel, BorderLayout.NORTH);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(textFieldPanelWrapper, BorderLayout.EAST);
}
public JComponent getMainPanel() {
return mainPanel;
}
private JMenuBar getMenuBar() {
return menubar;
}
private class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(),
e.getX(), e.getY());
}
}
}
private static void createAndShowGui() {
TestActions testActions = new TestActions();
JFrame frame = new JFrame("Test Actions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(testActions.getMainPanel());
frame.setJMenuBar(testActions.getMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
code borrowed from my answer here.
Edit
You ask in comment:
I appreciate the answer. However, could you make it a bit simpler to understand, I am fairly new to Java.
Sure, here is a simple JMenuBar that holds an edit JMenu that holds JMenuItems for copy, cut, and paste with just that code borrowed from my example. Note that as an aside, you should not setBounds on anything, you should instead set the rows and columns of your JTextArea, and that you should not use a static JTextArea, and in fact no Swing components should ever be static.
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultEditorKit;
public class DisplayText {
private JTextArea text;
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
public DisplayText(String title, String info) {
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
menu.add(new JMenuItem(textAction));
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
JFrame f = new JFrame(title);
f.setJMenuBar(menuBar);
Container c = f.getContentPane();
text = new JTextArea(info, 20, 50);
JScrollPane sp = new JScrollPane(text);
c.add(sp);
// f.setBounds(100,200, 500, 400 );
f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new DisplayText("Title", "This is info text");
}
}