How to set alignement in JTextPane? - java

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

Related

how can i transparent my JTextField and JLabel

My JTextField and JLabel are not Transparent in JPanel When JTable is visible it overlap between JTextField and JLabel. I want to show JTable when i Search something in Search (JTextField) but it overlap and JTable is not visible properly. Please Help here is my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import com.alee.laf.WebLookAndFeel;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JTable;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JScrollPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLayeredPane;
public class ButtonBarExample1 {
private JFrame frame;
private JTextField Search;
private JTable CategoryTable;
private DefaultTableModel model;
private static Connection con;
private String query;
private PreparedStatement PStat;
private ResultSet res;
private JScrollPane scrollPane;
private int Enter=0;
private JPanel panel;
private JLabel label;
private JLabel label_1;
private JTextField CategoryID;
private JTextField CategoryName;
private JPanel panel_1;
/**
* Launch the application.
*/
public static void main(String\[\] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WebLookAndFeel.install();
ButtonBarExample1 window = new ButtonBarExample1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ButtonBarExample1() {
initialize();
con=Database.Database();
}
public void remove(){
while(CategoryTable.getRowCount()>0) {
model.removeRow(0);
}
}
public void changed(){
if(Search.getText().length()==0){
panel.remove(scrollPane);
panel.repaint();
panel.revalidate();
}else{
try{
panel.add(scrollPane);
scrollPane.setViewportView(CategoryTable);
remove();
query="Select * from CategoryEntry where Category_Name like '"+Search.getText().trim()+"%'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
model=(DefaultTableModel)CategoryTable.getModel();
model.setRowCount(0);
CategoryTable.setRowHeight(30);
while(res.next()){
String CatID=res.getString("Category_ID");
String CatName=res.getString("Category_Name");
Object\[\] row= {CatID,CatName};
model.addRow(row);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
PStat.close();
res.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 934, 601);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 917, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 562, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panel.setLayout(null);
Search = new JTextField();
Search.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent e){
changed();
}
public void removeUpdate(DocumentEvent e){
changed();
}
public void insertUpdate(DocumentEvent e){
changed();
}
});
Search.setBounds(90, 11, 402, 31);
panel.add(Search);
Search.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(90, 41, 402, 127);
CategoryTable = new JTable();
CategoryTable.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int row=CategoryTable.getSelectedRow();
String TableClicked=(CategoryTable.getModel().getValueAt(row, 0)).toString();
try{
query="Select * from CategoryEntry where Category_ID='"+TableClicked+"'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
if(res.next()){
String CatID=res.getString("Category_ID");
CategoryID.setText(CatID);
String CatName=res.getString("Category_Name");
CategoryName.setText(CatName);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
PStat.close();
res.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
CategoryTable.setModel(new DefaultTableModel(
new Object\[\]\[\] {
},
new String\[\] {
"CategoryID", "CategoryName"
}
));
JLabel lblNewLabel = new JLabel("Search");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNewLabel.setBounds(21, 19, 46, 14);
panel.add(lblNewLabel);
panel_1 = new JPanel();
panel_1.setBounds(31, 53, 317, 76);
panel_1.setOpaque(false);
panel.add(panel_1);
panel_1.setLayout(null);
label_1 = new JLabel("Category ID");
label_1.setBounds(10, 14, 97, 18);
panel_1.add(label_1);
label_1.setFont(new Font("Tahoma", Font.BOLD, 11));
CategoryID = new JTextField();
CategoryID.setBounds(117, 11, 157, 25);
CategoryID.setBackground(new Color(255,255,255,128));
CategoryID.setOpaque(false);
panel_1.add(CategoryID);
CategoryID.setEditable(false);
CategoryID.setColumns(10);
label = new JLabel("Category Name");
label.setBounds(10, 42, 97, 18);
panel_1.add(label);
label.setFont(new Font("Tahoma", Font.BOLD, 11));
CategoryName = new JTextField();
CategoryName.setBounds(117, 39, 157, 25);
panel_1.add(CategoryName);
CategoryName.setEditable(false);
CategoryName.setColumns(10);
frame.getContentPane().setLayout(groupLayout);
}
}
Screenshot
I have solved it. Actually I made scrollpane transparency to true and also make it viewport to transparency to true like this.
scrollPane.setOpaque (true);
scrollPane.getViewPort ().setOpaque (true);

Cannot create JAR file-Main method not found

I'm trying to create a JAR of the given class.
I am using a tool called JARBuilder as Eclipse was of no help in creating JAR files.
When I try to create the JAR, it says that main method could be found, despite the fact that the main method is clearly defined.
Can someone please advise?
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField textField_1;
private JTextField textField_2;
private String name;
private String address;
private int port;
private JTextField textField;
public Login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 348);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(158, 44, 72, 16);
contentPane.add(lblUsername);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setBounds(135, 111, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblServerIp = new JLabel("Server IP");
lblServerIp.setBounds(158, 96, 56, 16);
contentPane.add(lblServerIp);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_1.setText("122.15.200.115");
textField_2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent key) {
}
});
textField_2.setBounds(135, 162, 116, 22);
textField_2.setText("8000");
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblPort = new JLabel("Port");
lblPort.setBounds(174, 146, 56, 16);
contentPane.add(lblPort);
JButton btnLogin = new JButton("Login");
btnLogin.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
newWindow();
}
});
btnLogin.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
newWindow();
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnLogin.setBounds(145, 197, 97, 43);
contentPane.add(btnLogin);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent key) {
if(key.getKeyCode()==KeyEvent.VK_ENTER)
{
if(!(textField.getText().equals("")))
{
name=textField.getText();
address=textField_1.getText();
port=Integer.parseInt(textField_2.getText());
try {
Chat_window window=new Chat_window(name, address, port);
dispose();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
textField.setColumns(10);
textField.setBounds(135, 60, 116, 22);
contentPane.add(textField);
JLabel lblAuthorprashantPandey = new JLabel("Author:Prashant Pandey");
lblAuthorprashantPandey.setBounds(125, 253, 186, 16);
contentPane.add(lblAuthorprashantPandey);
}
public void newWindow(){
name=textField.getText();
address=textField_1.getText();
port=Integer.parseInt(textField_2.getText());
try {
Chat_window window=new Chat_window(name, address, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dispose();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

java draw image over another

Hey I am trying to make a basic launcher and for the design I got an image. I want to make the exit button to be shown over the launcher image so you can see it. I dont know how I do it so I need help with it. Here is my code:
package launcher;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
*
* #author Daniel <Skype: daniel.gusdal>
*
* Current Date: 2. feb. 2014 Current Time: 21:46:52
* Project: 742 client. File Name: Launcher.java
*
*/
public class Launcher extends JFrame {
/**
* Generated serialVersionUID
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
static Point mouseDownCompCoords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mouseDownCompCoords = null;
final Launcher frame = new Launcher();
frame.setResizable(true);
frame.setUndecorated(true);
frame.setBackground(new Color(0, 255, 0, 0));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x
- mouseDownCompCoords.x, currCoords.y
- mouseDownCompCoords.y);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Launcher() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 593);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel Design = new JLabel("New label");
Design.setIcon(new ImageIcon(getClass().getResource("Launcher3.png")));
Design.setBounds(-158, -22, 1047, 592);
contentPane.add(Design);
ImageIcon img = new ImageIcon(getClass().getResource(
"Playnow.png"));
final JButton Playnow = new JButton(img);
Playnow.setBackground(null);
Playnow.setOpaque(false);
Playnow.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
}
#Override
public void mouseClicked(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
System.out.println(Playnow.getIcon());
}
#Override
public void mouseExited(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"Playnow.png")));
}
});
Playnow.setBounds(258, 442, 301, 46);
contentPane.add(Playnow);
final JButton Exit = new JButton();
Exit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(Exit.getIcon());
System.exit(0);
}
});
Exit.setIcon(new ImageIcon(Launcher.class.getResource("Exit.png")));
Exit.setOpaque(false);
Exit.setBounds(766, 59, 21, 21);
contentPane.add(Exit);
}
}
Don't set bounds. Learn to use Layout Managers.
Paint the image on a JPanel instead of using a JLabel
Put the JButton on the JPanel. Give that JPanel a GridBadLayout
Override the getPreferredSize() of the JPanel.
To switch between images you can use a flag like boolean icon1, icon2, icon3;. and repaint the JPanel the mouseXxx. Something like this
public void mouseClicked(MouseEvent e) {
icon1 = true;
icon2 = false;
icon3 = false;
imagePanel.repaint();
}
....
protected void paintComponent(Graphics g) {
if (icon1) {
g.drawImage(image1, .....);
}
if (icon2) { ... }
if (icon3) { ... }
}
pack() your frame.
Use Java naming convention. variables start with lower case letters.
Here's an example
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestButtonOverImage {
public TestButtonOverImage() {
JFrame frame = new JFrame("Test Card");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestButtonOverImage();
}
});
}
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setLayout(new GridBagLayout());
add(new JButton("StackOverflow Button"));
try {
img = ImageIO.read(new URL("http://d8u1nmttd4enu.cloudfront.net/designs/logo-stackoverflow-logo-design-99designs_447080~36d200d82d83d7b2e738cebd2a48de07180cef3a_largecrop"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 100, 100, 300, 300, this);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}

Change JButton look to custom picture

Is it possible to change the look of JButton to a custom picture? I want to use this picture as the button: http://i.stack.imgur.com/JMQMX.png instead of: http://i.stack.imgur.com/MXKUF.png
I have tried myself without succeed. Please help me! :)
Here is my code:
package launcher;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
public class Launcher extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
static Point mouseDownCompCoords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mouseDownCompCoords = null;
final Launcher frame = new Launcher();
frame.setResizable(false);
frame.setUndecorated(true);
frame.setBackground(new Color(0, 255, 0, 0));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x - mouseDownCompCoords.x,
currCoords.y - mouseDownCompCoords.y);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Launcher() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 593);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel Design = new JLabel("New label");
Design.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\Launcher2.png"));
Design.setBounds(-158, -22, 1047, 592);
contentPane.add(Design);
JButton Playnow = new JButton("");
Playnow.setOpaque(false);
Playnow.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\Playnow.png"));
Playnow.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
//Playnow.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\PlaynowHover.png"));
}
#Override
public void mouseClicked(MouseEvent e) {
//Playnow.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\PlaynowHover.png"));
}
});
Playnow.setBounds(258, 442, 301, 46);
contentPane.add(Playnow);
JButton Exit = new JButton("");
Exit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
final Launcher frame = new Launcher();
frame.dispose();
System.exit(0);
}
});
Exit.setBounds(766, 60, 19, 17);
contentPane.add(Exit);
}
}
I fixed it. There was something wrong with the picture thats why I couldnt see it...
try {
Playnow.setIcon(new ImageIcon(new URL("http://i.stack.imgur.com/JMQMX.png")));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this worked for me at the moment when i tried using ur code. however, if you wanna load it locally, you should try:
Playnow.setIcon(new ImageIcon(getClass().getResource("test.png")));
and test.png is in the same directory as the class file this code is in.
hope this helps :)
(I can't write comments yet so i write it as am awnser) I am not sure if this applies here, too but when i tried to change the icon of a Jlabel in my project, i had to set it invisible and after changing the icon visible again. Maybe it works if you try it like that.
Try this:
ImageIcon ic=new ImageIcon("C:/Users/Daniel/Pictures/Playnow.png")
JButton Playnow = new JButton(ic);
Playnow.setOpaque(false);

How can I add hyperlinks to a JTextPane without html?

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

Categories