How can I add hyperlinks to a JTextPane without html? - java

I have a JTextPane with a StyledDocument "doc" and I want when I doc.isertString(doc.getLength(), "http://www.google.com", attrs)
the JTextPane to show a hyperlink that can be clicked. I put "http://www.google.com" and attrs as an example because I really have no idea how to go about it. Surprisingly, I couldn't find anything useful online(without html, or HTMLDocument, etc.). I don't like how swing works with html and I prefer not to use it.
public class SSCCE extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSCCE frame = new SSCCE();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SSCCE() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet attrs = new SimpleAttributeSet();
try {
doc.insertString(doc.getLength(), "http://www.google.com", attrs);
} catch (BadLocationException e) {
e.printStackTrace();
}
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 422, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 248, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}

Define your own AttributeSet to keep hyperlink info. It should include e.g. blue color and custom attribute. Let's name it "URL". Add some text with the AttributeSet to the StyledDocument.
Then add a mouse listeners (Both motion and mouse listener). For any mouse event you can use viewToModel() to get offset for specified mouse position. Get a leaf element (text) for the offset and check whether the text Element has the attributes.
If it has do your actions (e.g. set mouse cursor to hand or process click on the URL).

+1 to StanislavL answer.Here is simple approach using HTML.
Well its not complicated to use HTML tags in your java code.The other way round may be complicated.I have done a short EG, easy to perform and understand,you can modify it and make it fit for your purpose.
CODE:
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JlabelLink extends JFrame {
private JPanel pan;
private JLabel website;
public JlabelLink() {
this.setTitle("jLabelLinkExample");
this.setSize(300, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
pan = new JPanel();
website = new JLabel();
website.setText("<html> Website : http://www.google.com/</html>");
website.setCursor(new Cursor(Cursor.HAND_CURSOR));
pan.add(website);
this.setContentPane(pan);
this.setVisible(true);
goWebsite(website);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new JlabelLink().setVisible(true);
}
});
}
private void goWebsite(JLabel website) {
website.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
try {
Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
} catch (IOException ex) {
Logger.getLogger(JlabelLink.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (URISyntaxException ex) {
}
}
});
}
}

Related

Can't see JDialog components when calling from another JDialog

i would like to know how can i see the components in my JDialog when calling it from another one.
I have one jDialog called Cargando1 which has a ProgressBar inside,this jDialog runs a method called iterate() when loading.
Otherwise i have another jDialog called login1, it has a button called btnIngresar, it validates some user and password stuff and then it should call Cargando1.
Also cargando1 calls a Frame called Principal after the progressbar has reach 100% but it doesn't matter.
I would like to know why when i called Cargando1 from Login1 it runs but i can't see the components on it.
Thank you for helping me!
This is the Jdialog called Login1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login1 extends JDialog implements ActionListener {
private JLabel lblUsuario;
private JTextField txtUsuario;
private JPasswordField jpassContrasena;
private JLabel lblContrasena;
private JButton btnIngresar;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Login1 dialog = new Login1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Login1() {
setBounds(100, 100, 225, 157);
getContentPane().setLayout(null);
lblUsuario = new JLabel("Usuario:");
lblUsuario.setFont(new Font("Courier New", Font.PLAIN, 11));
lblUsuario.setBounds(10, 12, 80, 20);
getContentPane().add(lblUsuario);
txtUsuario = new JTextField();
txtUsuario.setColumns(10);
txtUsuario.setBounds(101, 11, 95, 20);
getContentPane().add(txtUsuario);
jpassContrasena = new JPasswordField();
jpassContrasena.setBounds(101, 43, 95, 20);
getContentPane().add(jpassContrasena);
lblContrasena = new JLabel("Contrase\u00F1a:");
lblContrasena.setFont(new Font("Courier New", Font.PLAIN, 11));
lblContrasena.setBounds(10, 44, 80, 20);
getContentPane().add(lblContrasena);
btnIngresar = new JButton("Ingresar");
btnIngresar.addActionListener(this);
btnIngresar.setBounds(60, 80, 90, 23);
getContentPane().add(btnIngresar);
}
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == btnIngresar) {
actionPerformedBtnIngresar(arg0);
}
}
protected void actionPerformedBtnIngresar(ActionEvent arg0) {
char contrasena[] = jpassContrasena.getPassword();
String contrasenadef = new String(contrasena);
if (txtUsuario.getText().equals("Administrador") && contrasenadef.equals("admin"))
{ Principal.sesion = 'A';
JOptionPane.showMessageDialog(this, "Bienvenido, administrador", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else if (txtUsuario.getText().equals("Vendedor") && contrasenadef.equals("vendedor"))
{ Principal.sesion = 'V';
JOptionPane.showMessageDialog(this, "Bienvenido, vendedor", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else
{ JOptionPane.showMessageDialog(null, "Por favor ingrese un usuario y/o contraseƱa correctos", "Acceso denegado", JOptionPane.ERROR_MESSAGE);
}
}
}
This is the JDialog called cargando1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JProgressBar;
public class Cargando1 extends JDialog {
private final JPanel contentPanel = new JPanel();
private JProgressBar pgbCargando;
int porcentaje=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Cargando1 dialog = new Cargando1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.iterate();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Cargando1() {
setBounds(100, 100, 450, 154);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
pgbCargando = new JProgressBar(0,2000);
pgbCargando.setBounds(10, 11, 414, 93);
pgbCargando.setStringPainted(true);
contentPanel.add(pgbCargando);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
setContentPane(contentPanel);
}
void iterate() {
while (porcentaje < 2000)
{ pgbCargando.setValue(porcentaje);
try {Thread.sleep(100);}
catch (InterruptedException e) { }
porcentaje += 95;
}
Principal formulario1 = new Principal();
formulario1.setLocationRelativeTo(null);
this.dispose();
formulario1.setVisible(true);
}
}
The problem is in the iterate() method. Change your iterate() method to the following and give it a try.
void iterate() {
final Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (porcentaje < 2000) {
pgbCargando.setValue(porcentaje);
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
}
porcentaje += 95;
}
}
});
t.setDaemon(true);
t.start();
}
This will free up the main thread to do gui updates while the ProgressBar's value is modified in the background.
Two things to fix(and a note for the future):
Use Cargando1.setVisible(true) in Cargando1
DO NOT use Thread.sleep for swing, because javax.swing is not thread-safe. Your JDialog will freeze if you use Thread.sleep. Rather, use a Timer(javax.swing) with an ActionListener, or if you really want to use Thread.sleep, look into multithreading.
3. please indent better!!!! usually a new line with an extra 4 spaces after every {

How to set alignement in JTextPane?

I'm trying to make a chat application with Java; I chose to use JTextPane to display messages, because I read that it supports alignment. My problem is that I want to know how to align text in it. Like when I'm the sender, the sent message will be aligned in right; and when I'm the receiver it will be aligned in left.
Here is the code I wrote, but it aligns the whole text in right or left:
package memory;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.Toolkit;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextPane;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import javax.swing.ScrollPaneConstants;
import java.awt.Font;
#SuppressWarnings("serial")
public class ChatFrame extends JFrame {
private JPanel contentPane;
private JTextPane textPane= new JTextPane();;
private String msg=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ChatFrame frame = new ChatFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//setRemote Text
//false->me true->him
public void setTextToTextPane(String txt,boolean received) throws BadLocationException{
StyledDocument doc=textPane.getStyledDocument();
SimpleAttributeSet left = new SimpleAttributeSet();
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
SimpleAttributeSet right = new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
if(received==false){
doc.insertString(doc.getLength(), txt="\n", right);
doc.setParagraphAttributes(doc.getLength(), 1, right, false);
}else{
doc.insertString(doc.getLength(), txt="\n", left);
doc.setParagraphAttributes(doc.getLength(), 1, left, false);
}
}
/**
* Create the frame.
*/
public ChatFrame() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\PC-HOME\\Desktop\\design\\Speech Bubble-41.png"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 299, 380);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JScrollPane scrollPane_1 = new JScrollPane();
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE)
.addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE))
);
textPane.setFont(new Font("Consolas", Font.PLAIN, 14));
textPane.setEditable(false);
scrollPane_1.setViewportView(textPane);
JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Consolas", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.addKeyListener(new KeyAdapter() {
#SuppressWarnings("unchecked")
#Override
public void keyPressed(KeyEvent event) {
if(event.getKeyCode()==KeyEvent.VK_ENTER){
if(event.isShiftDown())
textArea.setText(textArea.getText()+"\n");
else{
msg=textArea.getText();
event.consume();
textArea.setText(null);
try {
//HelperMethods.sendMessageSocket(msg,port);
setTextToTextPane(msg,false);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> sendMsg=new ArrayList<>();
sendMsg.add(getTitle());
sendMsg.add(msg);
StaticData.sendMsg.add(sendMsg);
}
}
}
});
addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
String name=getTitle();
StaticData.frameMap.remove(name);
}
#Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
});
scrollPane.setViewportView(textArea);
panel.setLayout(gl_panel);
}
}
Does anyone know how to do that??
In "setTextToTextPane" in your code sample you're inserting "txt="\n"". This should be ""txt + "\n". Without this change it won't printing anything.
What you're doing in "setTextToPane" is correct in terms of setting the attributes. If you do a unit test it correctly positions the text left or right depending on the value of "received".

Java Resizable JLabel icon just keeps getting bigger

(EDIT 2) Hey guys i dont have a lot of time so i'll post this quick, i got the problem to happen in a smaller program:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.Color;
import javax.swing.border.LineBorder;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class Main extends JFrame {
private JPanel contentPane;
private JTextField txtWhatTheHell;
private static ArrayList<ImageIcon> thumbslist = new ArrayList<ImageIcon>();
public static DefaultListModel model = new DefaultListModel();
private static void initialize_pix() throws IOException
{
File filefolder = new File("pix");
File[] pictures = filefolder.listFiles();
for(File a: pictures)
{
Image tempimage = ImageIO.read(a);
ImageIcon perimage = new ImageIcon(tempimage);
thumbslist.add(perimage);
}
model.addElement(filefolder.toString());
}
public static ImageIcon resize(ImageIcon source, JLabel label)
{
int height = label.getHeight();
int width = label.getWidth();
Image original = source.getImage();
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = resized.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(original, 0, 0, width, height, null);
graphics.dispose();
ImageIcon result = new ImageIcon(resized);
return result;
}
public static void main(String[] args) {
try {
initialize_pix();
} catch (IOException e1) {
e1.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 731, 563);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
txtWhatTheHell = new JTextField();
txtWhatTheHell.setText("Text");
txtWhatTheHell.setEditable(false);
txtWhatTheHell.setColumns(10);
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JLabel label = new JLabel("");
label.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent a) {
label.setIcon(resize(thumbslist.get(0), label));
}
});
label.setBorder(new LineBorder(new Color(0, 0, 0)));
label.setBackground(Color.GRAY);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(toolBar, GroupLayout.DEFAULT_SIZE, 685, Short.MAX_VALUE)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 491, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(label, GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
.addComponent(txtWhatTheHell, GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))))
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(toolBar, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(txtWhatTheHell, GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(label, GroupLayout.PREFERRED_SIZE, 239, GroupLayout.PREFERRED_SIZE))
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE))
.addContainerGap())
);
JList list = new JList(model);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent a) {
if(list.isSelectionEmpty() == true)
{
return;
}
else
{
label.setIcon(thumbslist.get(0));
}
}
});
scrollPane.setViewportView(list);
contentPane.setLayout(gl_contentPane);
}
}
The file at the beginning is a file of pictures
I'm really not sure what's wrong with it
(EDIT 3) I did a a delay after each instance the resize listener is invoked, and the very first time, it is resized correctly, then it seems after that it starts to grow out of control
i think that #HovercraftFullOfEels thought this, but i just do not know exactly what to do in order to make it resize only once every time the frame is resized
You've got recursion of a sorts going on inside your component listener. Since you increase the size of the JLabel's icon within its own ComponentListener, the listener is notified of the change in size, which increase's the icon's size, which notifies the listener of the change in size....
A possible solution: consider turning off the listener within itself so that this recursion doesn't happen, and then turning it back on again. One way to do this is to simply remove and then re-add the listener within itself.
e.g.,
Label thumbchanger = new JLabel();
thumbchanger.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent a) {
// remove the *this* component listener before resizing
thumbchanger.removeComponentListener(this);
Mod current_mod = Globals.modList.get(list.getSelectedIndex());
ImageIcon new_icon = Globals.resize(current_mod.get_current(), thumbchanger);
thumbchanger.setIcon(new_icon);
// re-add the component listener after done resizing
thumbchanger.addComponentListener(this);
}
});
Another way is to use a boolean field local to the listener that you set within it.
thumbchanger.addComponentListener(new ComponentAdapter() {
private boolean resizing = false;
#Override
public void componentResized(ComponentEvent a) {
if (resizing) {
return;
}
resizing = true;
Mod current_mod = Globals.modList.get(list.getSelectedIndex());
ImageIcon new_icon = Globals.resize(current_mod.get_current(), thumbchanger);
thumbchanger.setIcon(new_icon);
resizing = false;
}
});

How to print setText() on multiple lines of a JLabel?

When I print out the raw text from a website, it will only put one line of text in the JLabel, but in the console it will do multiple lines each on their own line.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class closinggui extends JFrame {
private JPanel contentPane;
JLabel label;
JButton button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
closinggui frame = new closinggui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void code() throws IOException
{
Document document = Jsoup.connect("http://www.nbcwashington.com/weather/school-closings/").get();
Elements tags = document.select("p");
for (Element tag : tags) {
System.out.println(tag.text());
label.setText(tag.text());
}
}
public closinggui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 449, 524);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
label = new JLabel("");
label.setBounds(10, 45, 414, 440);
contentPane.add(label);
button = new JButton("get closings");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
code();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button.setBounds(164, 11, 89, 23);
contentPane.add(button);
}
}
As a sample it should print out multiple school closings like this:
Washington Yu Ying Public Charter School Closed
Whitman-Walker Health Open at 10am
Woodyard Road Nursery Open at 10am
But on the label all it shows is 1 line that isn't even a closing it is just in the same HTML tag as the others. So how do I make indents?
Try using html tags:
String txt = "<html>";
for (Element tag : tags) {
txt += tag.text() + "<br/>";
}
txt += "</html>";
label.setText(txt);
JLabel label = new JLabel("<html><span>this is <br> your text</span></html>");
or try
setText()
with html having
<br>
in it.
The <br> will break the lines properly.

JTextPane does not render span tag correctly

I have some code:
package main;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.StringWriter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DefaultCaret;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class LogConsole extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextPane logPane;
private HTMLDocument logDoc;
private HTMLEditorKit logKit;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LogConsole test = new LogConsole();
test.setVisible(true);
test.log("<span>Hello 1</span><br/>"); //Test 1
test.log("<span>Hello 2</span><br/>"); //Test 2
test.log("<span>Hello 3</span><br/>"); //Test 3
test.log("<span>Hello </span>"); //Test 4
test.log("<span>world!</span>"); //Test 5
test.printHTML();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Log some data...
* #param str
*/
public void log(String s){
s = s.replaceAll("\n", "<br/>");
try {
logKit.insertHTML(logDoc, logDoc.getLength(), s, 0, 0, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public void printHTML(){
try{
StringWriter writer = new StringWriter();
logKit.write(writer, logDoc, 0, logDoc.getLength());
String s = writer.toString();
System.out.println(s);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void clearLog(){
try {
logPane.setText("");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the frame.
*/
public LogConsole() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
.addContainerGap())
);
logPane = new JTextPane();
logPane.setContentType("text/html");
logPane.setEditable(false);
scrollPane.setViewportView(logPane);
contentPane.setLayout(gl_contentPane);
DefaultCaret caret = (DefaultCaret)logPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
logDoc = (HTMLDocument) logPane.getDocument();
logKit = (HTMLEditorKit) logPane.getEditorKit();
Font font = new Font("Consolas", Font.PLAIN, 14);
String bodyRule = String.format("body{font-family:%s;font-size:%spt",
font.getFamily(), font.getSize());
StyleSheet style = logDoc.getStyleSheet();
style.addRule(bodyRule);
}
}
I want to log some data from my app to a JTextPane, but I have some trouble with it.
First, when I add two span tag on two log() statement, it place a new line betwwen it (see Test4 - Test5).
So I think that JTextPane doesn't support inline tag, and all tag are block tag.
It's not a matter because each data log on each line is very 'good idle', you don't need to add "<br/>" on each data log, but I prefer to handle it myself
And if I insert 3 log() statement with "<br/>" at each log data (Test 1,2,3),
Line 1 write "Hello 1" and a new line, and a new line again.
Line 2 write "Hello 2" and one new line only
Line 3 write "Hello 3" and one new line
But Test1 and Test 2 have same statement form, and it produce two different way, why?
And if I change Test 2 to:
test.log("<span>Hello 2</span>"); //Test 2
It doesn't change the result!!!
Any one can explain these problem for me?
And how to fix these problem.
Thanks
The problem is not inserting span but your using insertHTML() which creates kind of surrounding paragrapph element.
The call works fine and does not create 2 lines
test.log("<span>Hello </span><span>World</span>");
Try this instead
public void log(String s){
s = s.replaceAll("\n", "<br/>");
try {
// logKit.insertHTML(logDoc, logDoc.getLength(), s, 0, 0, null);
logDoc.insertAfterEnd(logDoc.getCharacterElement(logDoc.getLength()), s);
} catch (Exception e) {
e.printStackTrace();
}
}
If I understand the question... It would be much easier if using a HTMLDocument#insertBeforeEnd(...) instead of the HTMLEditorKit#insertHTML(...):
logPane = new JTextPane();
logPane.setContentType("text/html");
logPane.setEditable(false);
//http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6700731
//Bug ID: JDK-6700731
//JTextPane now renders HTML paragraph tags differently in/out of tables
//logPane.setText("<html><table><tr><td><p id='log'>");
logPane.setText("<html><p id='log' style='margin-top:0'>");
//logKit.insertHTML(logDoc, logDoc.getLength(), s, 0, 0, null);
logDoc.insertBeforeEnd(logDoc.getElement("log"), s);

Categories