Refreshing Gui on solo thread - java

iam coding one app and i want to draw some marks and pictures over the map.But here i have the problem.When i push button iam starting the thread with 30 miliseconds delay.But in fact it looks like this task is running on main thread cause the gui stop refreshing and cant do anything with it.
Heres my code
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
public class MapDrawer extends JPanel
{
Graphics testGrafika;
DrawerThread drawingThread;
public MapDrawer(JPanel drawPanel)
{
drawPanel.add(this);
testGrafika=drawPanel.getGraphics();
paintComponent(testGrafika);
drawingThread=new DrawerThread();
drawingThread.run();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponents(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLUE);
g.fillRect(10, 25, 200, 200);
}
public Graphics getGraphics()
{
return testGrafika;
}
public class DrawerThread extends Thread implements Runnable
{
#Override
public void run()
{
while(true)
{
repaint();
try {
DrawerThread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
And this is my GUI class:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.CardLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.FlowLayout;
import javax.swing.border.EtchedBorder;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import soft.MapDrawer;
import soft.MapView;
import java.awt.Component;
import javax.swing.JToggleButton;
import javax.swing.JRadioButton;
import javax.swing.JInternalFrame;
import java.awt.Canvas;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
import javax.swing.JLayeredPane;
public class MainWindow {
private JFrame frame;
private JMenu MenuBasicActions;
private JInternalFrame mapFrameRef;
private JPanel drawPanelRef;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow()
{
initialize();
}
public JFrame getMainFrame()
{
return frame;
}
public JPanel getDrawPanel()
{
return drawPanelRef;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setVisible(true);
frame.setBounds(100, 100, 1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBarUpper = new JMenuBar();
frame.setJMenuBar(menuBarUpper);
MenuBasicActions = new JMenu("GPS Settings");
menuBarUpper.add(MenuBasicActions);
JMenuItem mntmNewMenuItem = new JMenuItem("New menu item");
MenuBasicActions.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("New menu item");
MenuBasicActions.add(mntmNewMenuItem_1);
JMenuItem mntmNewMenuItem_2 = new JMenuItem("New menu item");
MenuBasicActions.add(mntmNewMenuItem_2);
JMenu DevicesMenu = new JMenu("Devices");
menuBarUpper.add(DevicesMenu);
JMenuItem mntmNewMenuItem_3 = new JMenuItem("New menu item");
DevicesMenu.add(mntmNewMenuItem_3);
JMenuItem mntmNewMenuItem_4 = new JMenuItem("New menu item");
DevicesMenu.add(mntmNewMenuItem_4);
JMenu HelpMenu = new JMenu("Help");
menuBarUpper.add(HelpMenu);
JToolBar toolBar = new JToolBar();
toolBar.setOrientation(SwingConstants.VERTICAL);
frame.getContentPane().add(toolBar, BorderLayout.WEST);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
paint();
}
});
toolBar.add(btnNewButton_1);
JButton btnNewButton = new JButton("New button");
toolBar.add(btnNewButton);
JButton btnNewButton_2 = new JButton("New button");
toolBar.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("New button");
toolBar.add(btnNewButton_3);
toolBar.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{btnNewButton_1, btnNewButton}));
JInternalFrame mapFrame = new JInternalFrame("Military Tracking System");
mapFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.getContentPane().add(mapFrame, BorderLayout.CENTER);
mapFrame.setVisible(true);
JPanel drawPanel = new JPanel();
drawPanel.setOpaque(false);
mapFrame.setGlassPane(drawPanel);
drawPanel.setVisible(true);
drawPanel.setBorder(null);
//mapFrame.getContentPane().add(drawPanel, BorderLayout.CENTER);
frame.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{frame.getContentPane(), toolBar, btnNewButton_1, btnNewButton, btnNewButton_2, btnNewButton_3, menuBarUpper, MenuBasicActions, mntmNewMenuItem, mntmNewMenuItem_1, mntmNewMenuItem_2, DevicesMenu, mntmNewMenuItem_3, mntmNewMenuItem_4, HelpMenu}));
MapView hlavnaMapa=new MapView();
hlavnaMapa.Init(mapFrame);
mapFrameRef=mapFrame;
drawPanelRef=drawPanel;
}
public void paint()
{
MapDrawer drawer=new MapDrawer(drawPanelRef);
//drawer.paintComponent(drawer.getGraphics());
}
}
What i want to do is running gui on one thread and draw objects on other,so i can control gui.

In order to start the Thread you should invoke drawingThread.start(); instead of run().
start() will then start a new thread and call the method run() inside this thread. If you instead call run() it will run on the same thread as the caller.

Related

JAVA: Screenshot after JFrame change just black

I've written a program which makes a screenshot of JFrame by clicking on JMenuItem. If I only run the .java file in Eclipse, everything works and the screenshot shows the JFrame perfectly. But if I open the JFrame as a link from another JFrame, the screenshot is black instead of showing the JFrame. Here's my code:
JFrame1.java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JFrame1 extends JFrame {
static JFrame1 frame1 = new JFrame1();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void CloseFrame(){
super.dispose();
}
public JFrame1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
JButton ok = new JButton("OK");
getContentPane().add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CloseFrame();
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
}
});
}
}
With a button (ok) I can go to JFrame2.java.
JFrame2.java:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame2.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem screen = new JMenuItem("Screenshot");
screen.addActionListener(new AbstractAction() {
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
file.add(screen);
menubar.add(file);
setJMenuBar(menubar);
}
public JFrame2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
createMenuBar();
}
}
If I click now on "Screenshot", it is just black.
And if I run only JFrame2.java without running JFrame1.java before, the real image is saved.
Why does the screenshot is black after going from one JFrame1 to JFrame2?
You're painting from the wrong frame...
In your first frame, you are doing this...
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
Looks pretty harmless, but, in JFrame2 you are doing this...
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
And...
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
But, frame2 (inside JFrame2) is not visible on the screen.
This is why static is evil and should be avoid. This is also why you should not extend directly from something like JFrame. You can to easily get yourself into a knot of not knowing what is actually on the screen and what you are referencing...
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JavaApplication254 {
public static void main(String[] args) {
new JavaApplication254();
}
public JavaApplication254() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton btn = new JButton("Click me away...");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestPane testPane = new TestPane();
SnapshotAction snapshotAction = new SnapshotAction(testPane);
JMenuBar mb = new JMenuBar();
JMenu mnuFile = new JMenu("File");
mnuFile.add(snapshotAction);
mb.add(mnuFile);
JFrame frame = new JFrame("More Testing");
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel label = new JLabel("I be a bananan");
label.setOpaque(true);
label.setBackground(Color.YELLOW);
label.setForeground(Color.RED);
label.setBorder(
new CompoundBorder(
new LineBorder(Color.RED),
new EmptyBorder(20, 20, 20, 20)));
setLayout(new GridBagLayout());
add(label);
}
}
public class SnapshotAction extends AbstractAction {
private JComponent parent;
public SnapshotAction(JComponent parent) {
this.parent = parent;
putValue(NAME, "Take Snapshot...");
}
#Override
public void actionPerformed(ActionEvent e) {
if (parent.isDisplayable()) {
BufferedImage img = new BufferedImage(parent.getWidth(), parent.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
parent.printAll(g2d);
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Snapshot.png"));
Toolkit.getDefaultToolkit().beep();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(parent, "Failed to generate snapshot: " + ex.getMessage());
}
}
}
}
}
Which will output...

JPanel and JMenuBar to the same frame

I can't seem to add both a JMenuBar and a JPanel to my frame?
How come?
Code:
package proj;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Proj extends JFrame implements ActionListener {
Proj() {
setSize(400,300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setVisible(true);
JMenuBar rodMenu = new JMenuBar();
JMenu menu = new JMenu("Vis");
JMenuItem men_item1 = new JMenuItem("Statestik");
JPanel wrapper = new JPanel();
wrapper.setPreferredSize(new Dimension(380, 240));
wrapper.setBorder(BorderFactory.createLineBorder(Color.black));
setJMenuBar(rodMenu);
rodMenu.add(menu);
menu.add(men_item1);
add(wrapper);
}
public static void main(String[] args) {
new Proj();
}
}
With this code, the panel isn't added, only the menu... If I remove the menu, then the panel appears.
What do you mean panel not appearing? I could see both menu and panel with this code!
If the problem still persist try moving the setSize(), setResizable() etc block down like
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Proj extends JFrame implements ActionListener {
Proj() {
JMenuBar rodMenu = new JMenuBar();
JMenu menu = new JMenu("Vis");
JMenuItem men_item1 = new JMenuItem("Statestik");
JPanel wrapper = new JPanel();
wrapper.setPreferredSize(new Dimension(380, 240));
wrapper.setBorder(BorderFactory.createLineBorder(Color.black));
setJMenuBar(rodMenu);
rodMenu.add(menu);
menu.add(men_item1);
JButton b = new JButton("Test");
wrapper.add(b);
add(wrapper);
setSize(400, 300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new Proj();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Try adding with
this.getContentPane.add(wrapper)
instead of
add(wrapper)

How to open one JInternalFrame over another in JDesktopPane?

In my application, I am trying to open one JInternalFrame over another JInternalFrame in single JDesktopPane that implements MigLayout but it is displaying second internal frame beside first internal frame. Where am I going wrong?
Code
//MainClass.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import javax.swing.JDesktopPane;
import java.awt.Color;
#SuppressWarnings("serial")
public class MainClass extends JFrame {
private JPanel contentPane;
JDesktopPane desktopMain = new JDesktopPane();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainClass frame = new MainClass();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainClass() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 1368, 766);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnJinternalframe = new JMenu("Click Here");
menuBar.add(mnJinternalframe);
JMenuItem mntmOpenInternalFrame = new JMenuItem("Open Internal Frame");
mntmOpenInternalFrame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame1 frame = new JInternalFrame1(desktopMain
.getPreferredSize());
frame.setVisible(true);
desktopMain.add(frame);
}
});
mnJinternalframe.add(mntmOpenInternalFrame);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
desktopMain.setBackground(Color.WHITE);
contentPane.add(desktopMain, BorderLayout.CENTER);
desktopMain.setLayout(new MigLayout("", "[0px:1366px:1366px,grow,shrink 50,fill]", "[0px:766px:766px,grow,shrink 50,fill]"));
}
}
//JInternalFrame1.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
#SuppressWarnings("serial")
public class JInternalFrame1 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame1(Dimension d) {
setTitle("JInternalFrame1");
setBounds(0, 0, 1368, 766);
setVisible(true);
setSize(d);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
JButton btnClickMe = new JButton("Click Me");
btnClickMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)e.getSource());
if (container != null)
{
JDesktopPane desktop = (JDesktopPane)container;
JInternalFrame2 frame = new JInternalFrame2();
frame.setVisible(true);
desktop.add( frame );
}
}
});
panel.add(btnClickMe, "cell 7 5");
}
}
//JInternalFrame2.java
import javax.swing.JInternalFrame;
#SuppressWarnings("serial")
public class JInternalFrame2 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame2() {
setTitle("JInternalFrame2");
setBounds(100, 100, 450, 450);
setSize(500,500);
}
}
I found the solution,here is the code..
//MainClass.java
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicInternalFrameUI;
#SuppressWarnings("serial")
public class MainClass extends JFrame {
private JPanel contentPane;
static JDesktopPane desktopMain = new JDesktopPane();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainClass frame = new MainClass();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainClass() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, 1368, 766);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnJinternalframe = new JMenu("Click Here");
menuBar.add(mnJinternalframe);
JMenuItem mntmOpenInternalFrame = new JMenuItem("Open Internal Frame");
mntmOpenInternalFrame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame1 frame = new JInternalFrame1(desktopMain
.getPreferredSize());
frame.setVisible(true);
Dimension desktopSize = desktopMain.getSize();
frame.setSize(desktopSize);
frame.setPreferredSize(desktopSize);
desktopMain.add(frame);
dontmoveframe();
}
});
mnJinternalframe.add(mntmOpenInternalFrame);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
desktopMain.setBackground(Color.WHITE);
contentPane.add(desktopMain, BorderLayout.CENTER);
desktopMain.setLayout(new CardLayout(0, 0));
}
public static void dontmoveframe() {
try {
JInternalFrame[] frames = desktopMain.getAllFrames();
frames[0].setSelected(true);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
}
// Make first internal frame unmovable
JInternalFrame[] frames = desktopMain.getAllFrames();
JInternalFrame f = frames[0];
BasicInternalFrameUI ui = (BasicInternalFrameUI) f.getUI();
Component north = ui.getNorthPane();
MouseMotionListener[] actions = (MouseMotionListener[]) north
.getListeners(MouseMotionListener.class);
for (int i = 0; i < actions.length; i++) {
north.removeMouseMotionListener(actions[i]);
}
}
}
//JInternalFrame1.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
#SuppressWarnings("serial")
public class JInternalFrame1 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame1(Dimension d) {
setTitle("JInternalFrame1");
setBounds(0, 0, 1368, 766);
setVisible(true);
setSize(d);
setClosable(true);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
JButton btnClickMe = new JButton("Click Me");
btnClickMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)e.getSource());
if (container != null)
{
JDesktopPane desktopPane = getDesktopPane();
JInternalFrame2 f1 = new JInternalFrame2();
desktopPane.add(f1);//add f1 to desktop pane
f1.setVisible(true);
Dimension desktopSize = getDesktopPane().getSize();
f1.setSize(desktopSize);
f1.setPreferredSize(desktopSize);
MainClass.dontmoveframe();
}
}
});
panel.add(btnClickMe, "cell 7 5");
}
}
//JInternalFrame2.java
import javax.swing.JInternalFrame;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
#SuppressWarnings("serial")
public class JInternalFrame2 extends JInternalFrame {
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public JInternalFrame2() {
setTitle("JInternalFrame2");
setBounds(0, 0, 1366, 768);
setClosable(true);
getContentPane().setLayout(
new MigLayout("", "[][][][][][]", "[][][][][][]"));
JButton btnBack = new JButton("Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame2.this.dispose();
}
});
getContentPane().add(btnBack, "cell 5 5");
MainClass.dontmoveframe();
}
}

JMenu Item Action Listener is not being detected

I am making a library database for a school project and am having a little trouble with my menu. So the main problem is that in the Action Listener method when I write
(e.getSource()==m1Frame1)
my program does not detect the menu item and gives me an error. I have looked at multiple tutorials etc. online but cannot seem to find any way to fix it and make it so that if a specific item is clicked a specific action occurs. Any help/resolution regarding this issue would be much appreciated.
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import java.awt.event.*;
import javax.swing.Icon;
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Color;
public class m1 extends JFrame {
JPanel pane = new JPanel();
JFrame a = new JFrame("Main Frame");
JFrame b = new JFrame("Sub Frame");
JButton checkOutButton = new JButton("check");
JButton returnButton = new JButton("return");
JMenu mb2 = new JMenu("Books");
// mb2.setForeground(Color.white);
JMenu open = new JMenu("Students");
// open.setForeground(Color.white);
public m1() {
JMenuBar mb;
mb = new JMenuBar() {
public void paintComponent(Graphics g) {
g.drawImage(Toolkit.getDefaultToolkit().getImage("G:"), 0, 0, this);
}
};
setSize(400, 400);
setBackground(Color.BLACK);
setTitle("Screen 2");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb.add(open);
JMenuItem m1Frame1 = new JMenuItem("Create");
JMenuItem m1Frame2 = new JMenuItem("Delete");
JMenu m1Frame3 = new JMenu("Look-Up");
JMenuItem m1Frame4 = new JMenuItem("Check Fine");
JMenuItem m1Frame5 = new JMenuItem("Check Borrowed Books");
JMenuItem subM1 = new JMenuItem("Name");
JMenuItem subM2 = new JMenuItem("Student #");
open.add(m1Frame1);
open.add(m1Frame2);
open.add(m1Frame3);
open.add(m1Frame4);
open.add(m1Frame5);
m1Frame3.add(subM1);
m1Frame3.add(subM2);
mb.add(mb2);
JMenuItem m2Frame1 = new JMenuItem("Create");
JMenuItem m2Frame2 = new JMenuItem("Delete");
JMenu m2Frame3 = new JMenu("Look-Up");
JMenuItem subB1 = new JMenuItem("Title");
JMenuItem subB2 = new JMenuItem("Author");
JMenuItem subB3 = new JMenuItem("Category");
JMenuItem subB4 = new JMenuItem("ISBN");
JMenuItem m2Frame4 = new JMenuItem("Compare Star Rating");
JMenuItem m2Frame5 = new JMenuItem("Check If Checked Out");
JMenuItem m2Frame6 = new JMenuItem("Lost Book");
mb2.add(m2Frame1);
mb2.add(m2Frame2);
mb2.add(m2Frame3);
mb2.add(m2Frame4);
mb2.add(m2Frame5);
mb2.add(m2Frame6);
m2Frame3.add(subB1);
m2Frame3.add(subB2);
m2Frame3.add(subB3);
m2Frame3.add(subB4);
a.setJMenuBar(mb);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setSize(1280, 720);
a.setVisible(true);
b.setSize(600, 400);
m handler = new m();
pane.add(checkOutButton);
pane.add(returnButton);
add(pane);
checkOutButton.setVisible(false);
returnButton.setVisible(false);
checkOutButton.setBounds(60, 440, 220, 30);
returnButton.setBounds(60, 404, 100, 50);
checkOutButton.addActionListener(handler);
returnButton.addActionListener(handler);
}
public class m implements ActionListener, ItemListener {
public void actionPerformed(ActionEvent e) {
(e.getSource() == m1Frame1) {
a.setVisible(false);
setVisible(true);
checkOutButton.setVisible(true);
returnButton.setVisible(true);
}
}
public void itemStateChanged(ItemEvent e) {
}
}
public static void main(String[] args) {
m1 aa = new m1();
}
}
Ok, there are a few issues with your code, but I'll go over the two specifics that answer your question:
1) You're not adding your action listener to any of your MenuItems in your code. When I added your handler to the MenuItems using addActionListener(handler); It started triggering.
2) You're adding handler as the actionListener to two buttons that are invisible (and you've got other layout issues)

Inserting Images into a JTextPane Error

I asked about this before, but, I decided to start a new thread with a SCCE, it compiles sucessfully but it doesn't insert the image. Can anyone troubleshoot as to why it does this? Thanks, Chris.
Here is the full code:
package mathnotesplus;
import java.awt.Dimension;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.text.*;
/**
*
* #author ChrisCates
*/
public class MathNotesPlus extends JFrame implements TreeSelectionListener {
/**
* #param args the command line arguments
*/
public MathNotesPlus() {
setTitle("Math Notes Plus");
setSize(800, 600);
initUI();
}
JPanel panel;
JTextPane textpane;
JTree navigation;
StyledDocument document;
public void initUI(){
//The panel.
panel = new JPanel();
//Textpane and JTree
textpane = new JTextPane();
navigation = new JTree();
navigation.addTreeSelectionListener(this);
//Preferred Resolution Size
navigation.setPreferredSize(new Dimension(100, 600));
textpane.setPreferredSize(new Dimension(700, 600));
//Insertion of image into the document.
try {
document = (StyledDocument)textpane.getDocument();
Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon("sigma.png"));
document.insertString(document.getLength(), "ignored text", style);
} catch (BadLocationException e){
System.err.println("ERROR");
}
//Putting everything into the program.
panel.add(navigation);
panel.add(textpane);
add(panel);
pack();
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MathNotesPlus app = new MathNotesPlus();
app.setVisible(true);
}
});
}
#Override
public void valueChanged(TreeSelectionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Base on this working example (a very close variant of your code) that works, I can only guess that your code is failing because the image is not being found.
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class MathNotesPlus extends JFrame {
JPanel panel;
JTextPane textpane;
StyledDocument document;
public MathNotesPlus() {
setTitle("Math Notes Plus");
setSize(800, 600);
initUI();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void initUI(){
//The panel.
panel = new JPanel();
//Textpane
textpane = new JTextPane();
textpane.setPreferredSize(new Dimension(700, 600));
//Insertion of image into the document.
try {
Image image = ImageIO.read(new URL(
"http://pscode.org/media/stromlo1.jpg"));
document = (StyledDocument)textpane.getDocument();
Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
} catch (Exception e){
e.printStackTrace();
}
//Putting everything into the program.
panel.add(textpane);
add(panel);
pack();
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MathNotesPlus app = new MathNotesPlus();
app.setVisible(true);
}
});
}
}

Categories

Resources