Inserting Images into a JTextPane Error - java

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);
}
});
}
}

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...

shaped jdialog for transparency effect causing dragging issue

I have created shaped JDialog by adding transparency effect by
setBackground(new Color(0, 0, 0, 0); but it also adding drag listener to the dialog internally, problem is, when we drag by any other component in the dialog such as JTextfield, JList etc,. still the complete window is able to drag. so need to avoid adding internal drag listener to the jdialog. please anybody help me regarding this, here is my code.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyWindow extends JDialog {
private static final long serialVersionUID = 1L;
public MyWindow() {
JTextField text = new JTextField();
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("background.png"));
} catch (IOException e) {
}
JLabel label = new JLabel(new ImageIcon(myPicture));
setUndecorated(true);
setResizable(false);
setBackground(new Color(0, 0, 0, 0)); // creating issue
setSize(243, 474);
text.setBounds(18, 64, 212, 368);
add(text);
add(label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyWindow win = new MyWindow();
win.setVisible(true);
}
});
}
}
Thanks in advance,
Regards,
Bharath SR
Not sure if I fully understand your requirements or even your problem, but it sounds like you want a draggable dialog with no frame, just a background image and a component, and you don't want the components to trigger the drag event.
Give this a try. Hopefully it's what you're looking for. Feel free to ask questions.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DragDialog extends JDialog {
private int pointX;
private int pointY;
public DragDialog() {
JLabel backgroundLabel = createBackgroundLabel();
JTextField textField = createTextField();
setContentPane(backgroundLabel);
add(textField);
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private JTextField createTextField() {
final JTextField field = new JTextField(20);
field.setText("Type \"exit\" to terminate.");
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String text = field.getText();
if ("exit".equalsIgnoreCase(text)) {
System.exit(0);
}
}
});
return field;
}
private JLabel createBackgroundLabel() {
Image image = null;
try {
image = ImageIO.read(new URL("http://satyajit.ranjeev.in/images/icons/stackoverflow.png"));
} catch (IOException ex) {
Logger.getLogger(DragDialog.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel label = new JLabel(new ImageIcon(image));
label.setLayout(new GridBagLayout());
label.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
DragDialog.this.setLocation(DragDialog.this.getLocation().x + e.getX() - pointX,
DragDialog.this.getLocation().y + e.getY() - pointY);
}
});
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointX = e.getX();
pointY = e.getY();
}
});
return label;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DragDialog();
}
});
}
}

Setting a background image in JTabbedPane

I want to set a background image in a simple JTabbedPane. I used a Jlabel to set my background image. But i haven't been able to do so as i get a null pointer exception upon running.
Can anyone help with some more ideas?
Here is my code:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1
JPanel welcome;
JFrame frame;
ImageIcon image2;
public void createUI()
{
frame=new JFrame("JTabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcome= new JPanel(null);
welcome.setPreferredSize(new Dimension(1366,786));
image2 = new ImageIcon("icloud.jpg");
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
tp.addTab("Welcome", welcome);
lab1.setIcon(image2);
lab1.setBounds(0,0,1500,700);
frame.setSize(500,500);
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest tbp = new ImageTest ();
tbp.createUI();
}
}
EDIT:
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.*;
class ImageTest
{
JTabbedPane tp;
JLabel lab1;
JPanel welcome,w;
JFrame frame;
ImageIcon image2;
JButton b1;
public void createUI()
{
frame=new JFrame("JTabbedPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton();
welcome= new JPanel(new GridLayout(1,1,15,15));
w=new JPanel (new GridLayout(1, 1, 15, 15));
welcome.setPreferredSize(new Dimension(1366,786));
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
tp=new JTabbedPane();
Container pane = frame.getContentPane();
pane.add(tp);
lab1=new JLabel();
lab1.setIcon(icon);
w.setOpaque(false);
w.add(b1);
b1.setVisible(true);
welcome.add(lab1);
welcome.add(w);
tp.addTab("Welcome", welcome);
frame.setSize(500,500);
frame.pack();
frame.setVisible(true);
frame.setTitle("I-Cloud");
}
public static void main(String[] args)
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
ImageTest w = new ImageTest();
w.createUI();
}
}
You may just want to paint the image onto the panel you use for the JTabbedPane (as seen below). But as MadProgammer pointed out. It's most likely you are getting a null from the file location of your image file.
Note: when passing a String to the ImageIcon you are telling it to look for image in the file system. though this may work in a development environment from your IDE, it will not work at time of deployment Instead of reading the image file from the file system, you want to load it from the class path, as should be don with embedded resources, using a URL, which can be obtained by using MyClass.class.getResource(path)
So the way you should loading your image is like this
ImageIcon icon = new ImageIcon(ImageTest.class.getResource("icloud.jpg"));
And your image file would be in the same package as ImageIcon.java. You don't have to put the image in the same package, as you can specify a different path. You can find more info from the embedded resource tag wiki link above.
But back to the option of painting the background, see the example below. Instead of using a URL web link for the image though, you would read in your image file path as specified above.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TabBackground {
private BufferedImage bg;
public TabBackground() {
try {
bg = ImageIO.read(new URL("http://2.bp.blogspot.com/-wWANHD-Dr00/TtSmeY57ZXI/AAAAAAAABB8/t-fpXmQZ0-Y/s1600/Vector_by_Karpiu23.png"));
} catch (IOException ex) {
Logger.getLogger(TabBackground.class.getName()).log(Level.SEVERE, null, ex);
}
JPanel tabPanel = new JPanel(new GridBagLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
};
JPanel buttons = new JPanel(new GridLayout(4, 1, 15, 15));
buttons.setOpaque(false);
for (int i = 0; i < 4; i++) {
buttons.add(new JButton("Button"));
}
tabPanel.add(buttons);
JTabbedPane tabPane = new JTabbedPane();
tabPane.add("Panel with Bachground", tabPanel);
JFrame frame = new JFrame("Tabbed Pane with Background");
frame.setContentPane(tabPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(TabBackground.class.getName()).log(Level.SEVERE, null, ex);
}
new TabBackground();
}
});
}
}
You can add an image like this on Jframe:
tp.addTab("Welcome",new JLabel(new ImageIcon("bksqla_xlargecover.jpg")));

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();
}
}

Double List Item insertion in JTextPane

I have a button that inserts an unordered list item into a JTextPane. However, when I click on the button to insert a list item, two bullets are inserted instead of one. One bullet is inserted only during the first time insertion.
I cut out the functionality from my application and pasted the code into a small SSCCE (below) and the problem remains. Does anyone have any idea as to what might be happening here?
[The problem has been solved, below is the complete solved code. There are two ways to do this, refer to the functionality in the show and the bullets button]
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class Main {
private static Button2 show = new Button2 ("Show");
private static LIButton bullets = new LIButton("Bullets", HTML.Tag.UL);
private static JEditorPane pane = new JEditorPane();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() throws HeadlessException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.setPreferredSize(new Dimension(300, 300));
pane.setContentType("text/html");
frame.add(pane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(bullets);
panel.add(show);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class LIButton extends JButton {
static final String LI_HTML = "<HTML><BODY><UL><LI></LI></UL></BODY></HTML>";
public LIButton(String name, HTML.Tag parent) {
super(new HTMLEditorKit.InsertHTMLTextAction(
name, LI_HTML, HTML.Tag.UL, HTML.Tag.LI, HTML.Tag.BODY, HTML.Tag.UL));
}
}
static class Button2 extends JButton implements ActionListener {
static final String LI_HTML = "<HTML><BODY><UL><LI></LI></UL></BODY></HTML>";
public Button2(String name) {
super(name);
this.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent ae) {
HTMLDocument doc = (HTMLDocument) pane.getDocument();
HTMLEditorKit kit = (HTMLEditorKit) pane.getEditorKit();
try {
kit.insertHTML(doc, doc.getLength() - 1, LI_HTML, 0, 1, null);
} catch (BadLocationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The example below seems to work.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
public class Main {
private static LIButton bullets = new LIButton("Bullets", HTML.Tag.UL);
private static JTextPane pane = new JTextPane();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() throws HeadlessException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.setPreferredSize(new Dimension(300, 300));
pane.setContentType("text/html");
pane.setText("<HTML><BODY><UL></UL></BODY></HTML>");
frame.add(pane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(bullets);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class LIButton extends JButton {
static final String LI_HTML = "<LI>item</LI>";
public LIButton(String name, HTML.Tag parent) {
super(new HTMLEditorKit.InsertHTMLTextAction(
name, LI_HTML, parent, HTML.Tag.LI));
}
}
}

Categories

Resources