This is My Main class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.JButton;
public class Button extends JFrame {
public JPanel contentPane;
public SaveObject saveObject=new SaveObject();
public table frame1 ;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Button() {
NimbusLookAndFeel laf = new NimbusLookAndFeel();
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
frame1=new table();;
JButton btnNewButton = new JButton("SAVE");
btnNewButton.setBounds(151, 99, 120, 52);
contentPane.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveObject.save(frame1);
}
});
}
}
This is My second Class
import java.io.Serializable;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class table implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
public String[] title={"1","2","3","4","5"};
public DefaultTableModel tableModel=new DefaultTableModel(title,0);
JFrame a=new JFrame();
JTable table = new JTable(tableModel) ;
public JScrollPane scrollPane=new JScrollPane();
public Object[] object=new Object[title.length];
public int practiceNumber=0;
public String[] premlesave=new String[100];
public table()
{
scrollPane.setBounds(0, 0, 396, 188);
table.setFillsViewportHeight(true);
a.setVisible(true);
a.add(scrollPane);
} }
And this is My saveobject Class
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.imageio.stream.FileImageInputStream;
public class SaveObject
{
private ObjectOutputStream output;
private ObjectInputStream input;
public void save(Object o)
{
try{
output = new ObjectOutputStream(new FileOutputStream("mm.ser"));
output.writeObject(o);;
output.close();
output.flush();
}
catch(IOException e)
{}
}
}
And now I want use NimbusLookAndFeel laf = new NimbusLookAndFeel(); but this is not Serializable and show error. Why? This means I cant use the NimbusLookAndFeel?
Related
i have created a class to create the UserInterface of my program, my program has an instance of that UserInterface.
The UserIterface class has some listeners, my problem now is that i need to know from my program main class when my instance variable used to create the user interface raises events as for example tree valueChanged.
This is my userInterface class:
import java.awt.EventQueue;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTree;
import javax.swing.JSplitPane;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import org.eclipse.swt.widgets.Tree;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
public class UserInterfaceWindow implements TreeSelectionListener{
public JFrame frame;
public JTree tree;
public JPanel panel;
public JFileChooser fileChooser;
public IffFile iffFile;
public CustomRanAccFile inputRandAccFile;
/**
* Create the application.
*/
public UserInterfaceWindow() {
initialize();
frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 758, 549);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToolBar toolBar = new JToolBar();
frame.getContentPane().add(toolBar, BorderLayout.NORTH);
JButton btnOpenFile = new JButton("Open File");
btnOpenFile.addActionListener(new OpenButtonClick());
toolBar.add(btnOpenFile);
JButton button = new JButton("New button");
toolBar.add(button);
JSplitPane splitPane = new JSplitPane();
splitPane.setMinimumSize(new Dimension(300, 25));
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
tree = new JTree();
tree.setModel(new DefaultTreeModel(
new DefaultMutableTreeNode("File") {
/**
*
*/
private static final long serialVersionUID = 1L;
{
}
}
));
tree.setMinimumSize(new Dimension(200, 0));
tree.setMaximumSize(new Dimension(200, 64));
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(this);
splitPane.setLeftComponent(tree);
panel = new JPanel();
splitPane.setRightComponent(panel);
}
public class OpenButtonClick implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(fileChooser==null)
setUpFileChooser();
if(fileChooser.showOpenDialog(frame)==JFileChooser.APPROVE_OPTION){
try {
if(inputRandAccFile!=null)
inputRandAccFile.close();
inputRandAccFile= new CustomRanAccFile(fileChooser.getSelectedFile(),"rw");
iffFile=IffUtils.createIffFileInfo(inputRandAccFile);
IffUtils.obtainSubFileList2K14(iffFile, inputRandAccFile);
UserInterfaceWindow.this.setTreeElements(iffFile,UserInterfaceWindow.this.tree);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
public void setTreeElements(IffFile iffFile, JTree tree){
DefaultMutableTreeNode iffNode= new DefaultMutableTreeNode(iffFile);
DefaultTreeModel model= new DefaultTreeModel(iffNode, true);
for(IffBaseSubFile subFile: iffFile.getSubFileList()){
iffNode.add(new DefaultMutableTreeNode(subFile,false));
}
tree.setModel(model);
}
public void setUpFileChooser(){
fileChooser= new JFileChooser();
fileChooser.setDialogTitle("Select File");
FileNameExtensionFilter iffcdfFilter= new FileNameExtensionFilter("IFF/CDF Files","iff","CDF Files","cdf");
fileChooser.addChoosableFileFilter(iffcdfFilter);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileFilter(iffcdfFilter);
}
#Override
public void valueChanged(TreeSelectionEvent e) {
// TODO Auto-generated method stub
}
}
And this is Myprogram:
public class MyMain {
UserInterfaceWindow uiWindow;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyMain myMain= new MyMain();
myMain.uiWindow= new UserInterfaceWindow();
}
}
The event TreeSelectionEvent will be triggered when the user clicks on a node of the tree.
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();
}
});
}
}
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();
}
}
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);
}
});
}
}
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));
}
}
}