hyperlink with JLabel in Java Swing - java

i have a little problem with my code, meaning that hyperlink not showing under JLabel. I tried to resolve that problem by creating JLabel in different class and run the method in main class, but when i do that, it returning me only white square instead of label. no errors while compiling.
Main class:
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Desktop;
import java.awt.event.ActionListener;
import java.net.URI;
public class Main extends JFrame
{
static JLabel appicationStatute;
public Main() throws Exception
{
super();
registerWindowFrame = new JFrame("name");
registerWindowFrame.setSize(500,750);
registerWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
registerWindowFrame.setLayout(null);
registerWindowFrame.getContentPane().setBackground(Color.RED);
Statute status = new Statute();
status.setSize(status.getPreferredSize());
status.setLocation(10,450);
registerWindowFrame.getContentPane().add(status);
registerWindowFrame.setVisible(true);
}
public static void main (String [] args) throws Exception
{
new Main();
}
}
Statue class
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.*;
public class Statute extends JPanel {
private String text = "application statute";
private JLabel hyperlink = new JLabel(text);
public Statute() throws HeadlessException {
super();
hyperlink.setForeground(Color.BLUE.darker());
hyperlink.setCursor(new Cursor(Cursor.HAND_CURSOR));
hyperlink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI("http://www.codejava.net"));
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
public void mouseExited(MouseEvent e) {
hyperlink.setText(text);
}
#Override
public void mouseEntered(MouseEvent e) {
hyperlink.setText("<html><a href=''>" + text + "</a></html>");
}
});
}
}

Related

What else can be optimized how to use JTextField default text prompt function

What else can be optimized how to use JTextField default text prompt function
Thank you all for your answers
=============================================================================
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;[enter image description here][1]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class WindowActionEvent extends JFrame {
JTextField text;
JTextArea textShow;
JButton button;
ReaderListen listener;
public WindowActionEvent() throws HeadlessException {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());
text = new JTextField(10);
button = new JButton("读取");
textShow = new JTextArea(25,50);
textShow.setEditable(false);
listener = new ReaderListen();
listener.setJTextField(text);
listener.setJTextArea(textShow);
text.addActionListener(listener);
button.addActionListener(listener);
add(text);
add(button);
add(new JScrollPane(textShow));
}
}
class ReaderListen implements ActionListener {
JTextField text;
JTextArea textShow;
public void setJTextField(JTextField text) {
this.text = text;
}
public void setJTextArea(JTextArea textShow) {
this.textShow = textShow;
}
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File(text.getText()); //getDocument()
FileReader inOne = new FileReader(file);
BufferedReader inTwo = new BufferedReader(inOne);
String s = null;
while ((s = inTwo.readLine()) != null) {
textShow.append(s+"\n");
}
inOne.close();
inTwo.close();
} catch (Throwable e2) {
e2.printStackTrace();
}
}
}
public class Matematiktest extends WindowActionEvent {
public static void main(String[] args) {
WindowActionEvent win = new WindowActionEvent();
win.setBounds(100,100,1000,500);
win.setTitle("处理ActionEvent事件");
}
}
This is the code I checked about the default text prompt function of JTextField but I don’t know where it should be placed or used
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class JTextFieldHintListener implements FocusListener {
private String hintText;
private JTextField textField;
public JTextFieldHintListener(JTextField jTextField,String hintText) {
this.textField = jTextField;
this.hintText = hintText;
jTextField.setText(hintText); //默认直接显示
jTextField.setForeground(Color.GRAY);
}
#Override
public void focusGained(FocusEvent e) {
//获取焦点时,清空提示内容
String temp = textField.getText();
if(temp.equals(hintText)) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
}
#Override
public void focusLost(FocusEvent e) {
//失去焦点时,没有输入内容,显示提示内容
String temp = textField.getText();
if(temp.equals("")) {
textField.setForeground(Color.GRAY);
textField.setText(hintText);
}
}
}

How to keep the Auto Clicker running without the program stopping it immediately after running

package com.company.Iguana;
import java.awt.*;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.KeyEvent;
public class Main {
public static boolean Clicking = true;
public static Robot robot;
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == 'x')
Clicking = true;
if(e.getKeyChar() == 'v')
Clicking = false;
if(Clicking == true)
while(true){
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
}
#Override
public void keyReleased(KeyEvent e) {
}
};
}
}
I'm trying to make it so whenever I press x the AutoClicker start and Stop it when I press v but once I run the code it just says public static void main(String[] args) but when I put in static it says 23:9
java: non-static variable this cannot be referenced from a static context
Line 23:9 is the this.addKeyListener( new KeyListener() {
..................................................................................................................................................................................................................

Move JLabel in GridLayout java swing

I'm trying to move a Robot represented by a JLabel into a GridLayout.
The move is made but the display of the JLabel is only done for the final finishing square.
I would like to see the move from box to box. How can I do ?
import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel, Vector<Case> listeDeCases) {
for (int i=0; i<5; i++) {
LayoutManager layout = panel.getLayout();
try { Thread.sleep(1000);
panel.remove(panel.getComponent(i));
panel.add(this, i);
panel.doLayout();
}
catch (InterruptedException e) {}
}
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}
try { Thread.sleep(1000);
Don't do this on the AWT Event Dispatch Thread (EDT). Your GUI can't be repainted because this code is blocking it.
Use javax.swing.Timer (not to be confused with any other Timer) to set an event for the next time robot needs to be moved. You will need to keep track of state outside of local variables.
import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
import javax.swing.Timer;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel) {
Robot currentRoot = this;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
for (int i=0; i<5; i++) {
panel.remove(panel.getComponent(i));
panel.add(currentRoot, i);
panel.doLayout();
}
}
};
new Timer(delay, taskPerformer).start();
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}

Java task not updating jlabel

Question I have is I am trying to update my gui with a timer(this works and changes the image for mypic but, it will not update mytext label for some weird reason any help would be very much appreciated!
*I should add that mytext isn't showing up at all on my gui since introducing the timer...but mypic does????
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by xxxxxxzz on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = null;
JLabel mypic = null;
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
//Tried setting it like this and still doesn't work
// myText = new JLabel("HOT");
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
UPDATE with suggestions still isn't working..
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by jsnow on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = new JLabel();
JLabel mypic = new JLabel();
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
Here's a working solution which you can tailor to your use. The cause seemed to be the way you had tried to display the Components rather than the code in your action listener.
Your approach was just replacing myText with myPic when you initially set up the JFrame. Instead you need to use a layout manager. The example I've given is with overlaying using JLayeredPane. You may wish to use a layout manager instead if this is not the desired outcome, see the Oracle Tutorial on using layout managers.
Widget class
package widget;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Widget extends JFrame {
private static final int UPDATE_TICK = 5_000;
private static final int WIDGET_WIDTH = 150;
private static final int WIDGET_HEIGHT = 150;
private JLabel myText = new JLabel();
private JLabel myPic = new JLabel();
private Weather weather = new Weather();
private Timer simpleTimer;
public void createAndShow() {
setUndecorated(true);
setSize(WIDGET_WIDTH, WIDGET_HEIGHT);
Shape shape = new Ellipse2D.Float(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
// AWTUtilities.setWindowShape(this, shape);
setShape(shape); // do this instead
myText.setHorizontalAlignment(JLabel.CENTER);
myPic.setHorizontalAlignment(JLabel.CENTER);
JLayeredPane layered = new JLayeredPane();
myText.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
myPic.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
layered.add(myPic, 1, 0);
layered.add(myText, 2, 0);
add(layered);
simpleTimer = new Timer(UPDATE_TICK, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
update();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
simpleTimer.start();
}
private void update() {
myText.setText(weather.getTemp());
myPic.setIcon(new ImageIcon(weather.getImage(WIDGET_WIDTH, WIDGET_HEIGHT)));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Widget w = new Widget();
w.createAndShow();;
}
});
}
}
Weather class for demonstration purposes
package widget;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Weather {
private static final Random rand = new Random();
private static final Color[] randColors = {Color.YELLOW,
Color.GREEN,
Color.WHITE};
public String getTemp() {
return Integer.toString(rand.nextInt(100));
}
public BufferedImage getImage(int width, int height) {
int colorIndex = rand.nextInt(randColors.length);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
img.setRGB(x, y, randColors[colorIndex].getRGB());
}
}
return img;
}
}

Adding copy action in windows to java app

I want to get the event like crtl+c or right click copy in windows , that could do the event to java application running ,
that means if someone copies some text , that should be pasted into the java application textarea...
i have made the java application and it can accept arguments through main method.
but how to trigger event from windows to java..
The simplest way is to monitor changes to the Toolkit.getSystemClipboard
There are two ways to do this. You can monitor changes to the DataFlavour, but this will only help if the data flavor changes, not the content and/or you could monitor the contents of the clipboard and update your view when it's content changes...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ClipboardMonitor {
public static void main(String[] args) {
new ClipboardMonitor();
}
public ClipboardMonitor() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
public TestPane() {
textArea = new JTextArea(10, 10);
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(new FlavorListener() {
#Override
public void flavorsChanged(FlavorEvent e) {
setText(getClipboardContents());
}
});
Thread t = new Thread(new ContentsMonitor());
t.setDaemon(true);
t.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected String getClipboardContents() {
String text = null;
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
try {
Transferable contents = clipboard.getContents(TestPane.this);
text = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
ex.printStackTrace();
}
}
return text;
}
protected void setText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
textArea.setText(text);
}
});
}
public class ContentsMonitor implements Runnable {
#Override
public void run() {
String previous = getClipboardContents();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
String text = getClipboardContents();
if (text != null && !text.equals(previous)) {
setText(text);
previous = text;
}
}
}
}
}
}

Categories