Margins with LineBorders - border

I want to have a JTextArea with a LineBorder and leave a little padding between the text and the LineBorder.
Is this possible with the standard classes or do I need a custom "DoubleLine" border (one with the color and one with the margin)?
Some sample code is below...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class TextAreaLineBorder extends JFrame
{
private static final long serialVersionUID = 1L;
private class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public MyPanel()
{
setLayout(new FlowLayout());
JTextArea ta = new JTextArea("Some text");
ta.setSize(200, 50);
boolean useDefaultBorder = false;
if (useDefaultBorder)
{
// Setting the margin works fine, with the default border
ta.setMargin(new Insets(12, 12, 12, 12));
Border b = ta.getBorder();
Insets defaultInsets = b.getBorderInsets(ta);
System.out.println("Default Insets: "
+ defaultInsets);
}
else
{
// Try using a non-default LineBorder
LineBorder lb = (LineBorder) BorderFactory.createLineBorder(Color.YELLOW, 2);
ta.setBorder(lb);
// TODO: What should be done so that the LineBorder has Insets?
ta.setMargin(new Insets(12, 12, 12, 12));
Insets lineBorderInsets = lb.getBorderInsets(ta);
System.out.println("LineBorder Insets: " + lineBorderInsets);
}
add(ta);
}
}
public TextAreaLineBorder()
{
setResizable(true);
setName(getClass().getSimpleName());
setTitle("My Frame");
setSize(300, 300);
JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
// Add the panel
tabbedPane.addTab("Button panel", new MyPanel());
add(tabbedPane, BorderLayout.CENTER);
getContentPane().add(tabbedPane);
}
private static void createAndShowGUI()
{
// Create and set up the window.
TextAreaLineBorder frame = new TextAreaLineBorder();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
createAndShowGUI();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
});
}
}

You can add the JTextArea to a JScrollPane and put the border around that.
JTextArea JTA = new JTextArea();
JScrollPane JSP = new JScrollPane(JTA);
JSP.setBorder(BorderFactory.createLineBorder(Color.blue));

I created a class that helped me solve this problem. The same solution can likely be used for all JTextComponents.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JTextAreaWithPaddedBorder extends JTextArea
{
// **********************************************************************
// To modify the sample program using GWT Designer, uncomment this code
// **********************************************************************
// public JTextAreaWithPaddedBorder()
// {
// }
//
// /**
// * Bogus Constructor
// *
// * #wbp.parser.constructor (Use this method in the GWT Designer)
// */
//
// public JTextAreaWithPaddedBorder(int ignore)
// {
// createAndShowGUI();
// }
// **********************************************************************
// To modify the sample program using GWT Designer, uncomment this code
// **********************************************************************
public static void createAndShowGUI()
{
// Create and set up the frame
JFrame frmTextareawithpaddedborder = new JFrame();
frmTextareawithpaddedborder.setTitle("TextAreaWithPaddedBorder");
frmTextareawithpaddedborder.setName("frmTextareawithpaddedborder");
frmTextareawithpaddedborder.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTextareawithpaddedborder.setBounds(100, 100, 514, 495);
frmTextareawithpaddedborder.setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frmTextareawithpaddedborder.setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 5, 490, 395);
scrollPane.setName("scrollPane");
contentPane.add(scrollPane);
final JTextAreaWithPaddedBorder textArea = new JTextAreaWithPaddedBorder();
textArea.setBorder(new LineBorder(new Color(0, 0, 0), 2));
textArea.setName("textArea");
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
String text = "The iPhone is a line of smartphones designed and marketed by Apple Inc. The first iPhone was unveiled by Steve Jobs, then CEO of Apple, on January 9, 2007,[1] and released on June 29, 2007. The 5th generation iPhone, the iPhone 4S, was announced on October 4, 2011, and released 10 days later. An iPhone can function as a video camera (video recording was not a standard feature until the iPhone 3GS was released), a camera phone, a portable media player, and an Internet client with email and web browsing capabilities, can send texts and receive visual voicemail, and has both Wi-Fi and cellular data (2G and 3G) connectivity. The user interface is built around the device's multi-touch screen, including a virtual keyboard rather than a physical one.";
textArea.setText(text);
textArea.append("\n\nThis is the text within the TextArea. As the border of the TextArea is changed, the text should display properly.");
contentPane.setLayout(null);
textArea.setBackground(Color.WHITE);
scrollPane.setViewportView(textArea);
btnChangeMargins = new JButton("Change Margins");
btnChangeMargins.setBounds(13, 430, 152, 23);
btnChangeMargins.setName("btnChangeMargins");
btnChangeMargins.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
long t = (new Date()).getTime() % 100;
int top = (int) (t * 18) % 15;
int bottom = (int) (t * 34) % 15;
int left = (int) (t * 52) % 15;
int right = (int) (t * 52) % 15;
Insets insets = new Insets(top, left, bottom, right);
textArea.setMargin(insets);
}
});
contentPane.add(btnChangeMargins);
btnChangeBGColor = new JButton("Change BG Color");
btnChangeBGColor.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
long t = (new Date()).getTime() % 100;
int r = 100 + (int) (t * 18) % 100;
int g = 100 + (int) (t * 34) % 100;
int b = 100 + (int) (t * 52) % 100;
Color c = new Color(r, g, b);
textArea.setBackground(c);
}
});
btnChangeBGColor.setBounds(178, 430, 152, 23);
btnChangeBGColor.setName("btnChangeBGColor");
contentPane.add(btnChangeBGColor);
btnChangeBorder = new JButton("Change Border");
btnChangeBorder.setBounds(343, 430, 152, 23);
btnChangeBorder.setName("btnChangeBorder");
btnChangeBorder.addActionListener(new ActionListener()
{
int last = 0;
#Override
public void actionPerformed(ActionEvent e)
{
Border nextBorder;
switch (last++ % 8)
{
case 0:
nextBorder = BorderFactory.createLoweredBevelBorder();
break;
case 1:
nextBorder = BorderFactory.createEmptyBorder();
break;
case 2:
nextBorder = BorderFactory.createEtchedBorder();
break;
case 3:
nextBorder = BorderFactory.createLineBorder(Color.black, 2);
break;
case 4:
nextBorder = BorderFactory.createRaisedBevelBorder();
break;
case 5:
nextBorder = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.red, 3), BorderFactory
.createLoweredBevelBorder());
break;
case 6:
nextBorder = BorderFactory.createMatteBorder(2, 15, 1, 15, new Color(255, 0, 0));
break;
case 7:
nextBorder = BorderFactory.createTitledBorder("Titled Border");
break;
default:
nextBorder = BorderFactory.createTitledBorder("Titled Border");
}
textArea.setBorder(nextBorder);
}
});
contentPane.add(btnChangeBorder);
frmTextareawithpaddedborder.setVisible(true);
}
private static final long serialVersionUID = 1L;
private static JButton btnChangeMargins;
private static JButton btnChangeBGColor;
private static JButton btnChangeBorder;
#Override
public void setBorder(Border border)
{
int paddingWidth = 0;
Border currentBorder = getBorder();
if (currentBorder != null)
{
// The padding width will be the minimum width specified in the insets
Insets insets = getMargin();
paddingWidth = Math.min(insets.bottom, insets.top);
paddingWidth = Math.min(paddingWidth, insets.left);
paddingWidth = Math.min(paddingWidth, insets.right);
}
/*
* Use a LineBorder for the padding.
*
* The color must be the same as the background color of the TextComponent
*/
super.setBorder(new CompoundBorder(border, BorderFactory.createLineBorder(getBackground(), paddingWidth)));
}
#Override
public void setBackground(Color c)
{
super.setBackground(c);
Border b = getBorder();
if (b != null)
{
setBorder(((CompoundBorder) b).getOutsideBorder());
}
}
#Override
public void setMargin(Insets m)
{
super.setMargin(m);
Border b = getBorder();
if (b != null)
{
setBorder(((CompoundBorder) b).getOutsideBorder());
}
}
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
createAndShowGUI();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}

Related

how to change media in mediaplayer not mediaplayercomponent in vlcj?

I'm making desktop application using swing and vlcj. I had divided frame into two part one side webbrowser which is having url of several videos and in another panel vlcj to play that url in mediaplayer. The first url you choose works just fine and is displayed in the player. The thing is, after I choose another url I want the first one to be replaced with the second one. What is the correct way to dispose the first media and then play the second one? The second problem is I had set the vlcj in panel but its openning video in vlc direct 3d output can you tell me why it is not openning in panel canvas.
This is the code what I tried:
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.binding.LibVlcConst;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
/**
*
* #author biznis
*/
public class NewJFrame extends javax.swing.JFrame {
JScrollPane scrollableTextArea;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
//JFrame jFrame2 = new JFrame("vlcj Tutorial");
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
canvas1.setBackground(Color.black);
jPanel2.setLayout(new BorderLayout());
jPanel2.setPreferredSize(new Dimension(200,300));
jPanel2.add(canvas1, BorderLayout.CENTER);
// frame.add(jPanel2, BorderLayout.NORTH);
// frame.add(p, BorderLayout.CENTER);
EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));
//jPanel2.setLayout(new java.awt.CardLayout());
//jFrame2.setVisible(true);
//jFrame2.setLocation(100, 100);
JPanel p1 = new JPanel();
p1.setBounds(100, 900, 105, 200);
jPanel2.add(p1, BorderLayout.SOUTH);
JButton playbutton = new JButton();
playbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/play.png"));
// this.setSize(800,450);
playbutton.setBounds(50, 50, 150, 100);
playbutton.setToolTipText("Play");
p1.add(playbutton);
JButton pausebutton = new JButton();
pausebutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/pause.png"));
pausebutton.setToolTipText("pause");
pausebutton.setBounds(80, 50, 150, 100);
p1.add(pausebutton);
JButton previousbutton = new JButton();
previousbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/previous.png"));
previousbutton.setBounds(90, 50, 150, 100);
previousbutton.setToolTipText("Skip back");
p1.add(previousbutton);
JButton nextbutton = new JButton();
nextbutton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/next.png"));
nextbutton.setBounds(90, 50, 150, 100);
nextbutton.setToolTipText(" Skip forward");
p1.add(nextbutton);
JButton captureButton = new JButton();
captureButton.setIcon(new ImageIcon("C:/Users/biznis/Desktop/Newspaper/sangbadpratidin/d/icons8-unsplash-26.png"));
captureButton.setToolTipText("capture");
captureButton.setBounds(80, 50, 150, 100);
p1.add(captureButton);
JSlider volumeSlider = new JSlider();
volumeSlider.setMinimum(LibVlcConst.MIN_VOLUME);
volumeSlider.setMaximum(LibVlcConst.MAX_VOLUME);
volumeSlider.setPreferredSize(new Dimension(100, 40));
volumeSlider.setToolTipText("Change volume");
p1.add(volumeSlider);
JSlider js = new JSlider();
p1.add(js);
// mediaPlayer.playMedia("D:\\test\\192.168.2.201_01_20180124_153000.avi");
js.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (js.getValue() / 100 < 1) {
mediaPlayer.setPosition((float) js.getValue() / 100);
}
}
});
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
js.setValue(Math.round(mediaPlayer.getPosition() * 100));
}
});
timer.start();
pausebutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mediaPlayer.pause();
// or mediaPlayer.pause() depending on what works.
final long time = mediaPlayer.getTime();
System.out.println(time);
}
});
playbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mediaPlayer.play();
}
});
previousbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
mediaPlayer.skip(-10000);
}
});
nextbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mediaPlayer.skip(1000);
}
});
volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
mediaPlayer.setVolume(volumeSlider.getValue());
}
});
captureButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File file3 = new File("C:/Test/");
mediaPlayer.saveSnapshot(file3);
try {
BufferedImage image3 = ImageIO.read(file3);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
JFXPanel jfxPanel = new JFXPanel();
jPanel1.add(jfxPanel);
// Creation of scene and future interactions with JFXPanel
// should take place on the JavaFX Application Thread
Platform.runLater(() -> {
WebView webView = new WebView();
WebEngine wb1 = webView.getEngine();
jfxPanel.setScene(new Scene(webView));
wb1.load("");
wb1.getLoadWorker().stateProperty()
.addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SCHEDULED) {
frame.setTitle(wb1.getLocation());
String trgurl = wb1.getLocation();
System.out.println(trgurl);
if (trgurl.matches("(.*)video=(.*)")) {
int n = trgurl.indexOf("video=");
//String str1 = Integer.toString(n);
System.out.println(n + 6);
int len = trgurl.length();
System.out.println("string length is: " + trgurl.length());
System.out.println(trgurl.substring(n+6,len));
String find = "file:" +trgurl.substring(n+6,len);
System.out.println(find);
// mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));
mediaPlayer.prepareMedia(find);
mediaPlayer.start();
JScrollPane scrollableTextArea = new JScrollPane(jPanel2);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
}
}
});
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel1.setPreferredSize(new Dimension(200, 300));
canvas1 = new java.awt.Canvas();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(500, 300));
getContentPane().setLayout(new java.awt.GridLayout());
getContentPane().add(jPanel2);
jPanel1.add(canvas1);
getContentPane().add(jPanel1);
// getContentPane().add(sp);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(final String[] args) {
/* Set the Nimbus look and feel */
new NativeDiscovery().discover();
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame = new NewJFrame();
frame.setVisible(true);
}
});
}
private static NewJFrame frame;
// Variables declaration - do not modify
private java.awt.Canvas canvas1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration
}
in jpanel1 im openning vlcj and jpanel2 webview. Please help. Thanks in advance.
This is exception log when i click on next link of video:
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: The video surface component must be displayable
at uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface.attach(CanvasVideoSurface.java:75)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.attachVideoSurface(DefaultEmbeddedMediaPlayer.java:156)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.onBeforePlay(DefaultEmbeddedMediaPlayer.java:315)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.play(DefaultMediaPlayer.java:705)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.playMedia(DefaultMediaPlayer.java:222)
at javaapplication6.NewJFrame$9.changed(NewJFrame.java:231)
at javaapplication6.NewJFrame$9.changed(NewJFrame.java:211)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.web.WebEngine$LoadWorker.updateState(WebEngine.java:1287)
at javafx.scene.web.WebEngine$LoadWorker.dispatchLoadEvent(WebEngine.java:1388)
at javafx.scene.web.WebEngine$LoadWorker.access$1200(WebEngine.java:1280)
at javafx.scene.web.WebEngine$PageLoadListener.dispatchLoadEvent(WebEngine.java:1267)
at com.sun.webkit.WebPage.fireLoadEvent(WebPage.java:2499)
at com.sun.webkit.WebPage.fwkFireLoadEvent(WebPage.java:2343)
at com.sun.webkit.WebPage.twkProcessMouseEvent(Native Method)
at com.sun.webkit.WebPage.dispatchMouseEvent(WebPage.java:807)
at javafx.scene.web.WebView.processMouseEvent(WebView.java:1045)
at javafx.scene.web.WebView.lambda$registerEventHandlers$32(WebView.java:1168)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$null$293(EmbeddedScene.java:256)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.EmbeddedScene.lambda$mouseEvent$294(EmbeddedScene.java:244)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
Thnx i had solved the problem by taking left and right panel with scroll pane.
import java.awt.*;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.*;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
public class MyTestClass extends JFrame {
EmbeddedMediaPlayerComponent playerCmpt;
public MyTestClass() {
new NativeDiscovery().discover();
EmbeddedMediaPlayerComponent playerCmpt = new EmbeddedMediaPlayerComponent();
playerCmpt.setPreferredSize(new Dimension(200, 100));
JPanel leftPane = new JPanel();
leftPane.setPreferredSize(new Dimension(100, 100));
JFXPanel jfxPanel = new JFXPanel();
leftPane.add(jfxPanel);
//jPanel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//jPanel1.setBorder(new EmptyBorder(20, 20, 20, 20));
// Creation of scene and future interactions with JFXPanel
// should take place on the JavaFX Application Thread
Platform.runLater(() -> {
WebView webView = new WebView();
WebEngine wb1 = webView.getEngine();
jfxPanel.setScene(new Scene(webView));
wb1.load("");
wb1.getLoadWorker().stateProperty()
.addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
if (newState == Worker.State.SCHEDULED) {
// this.setTitle(wb1.getLocation());
String trgurl = wb1.getLocation();
System.out.println(trgurl);
if (trgurl.matches("(.*)video=(.*)")) {
int n = trgurl.indexOf("video=");
//String str1 = Integer.toString(n);
System.out.println(n + 6);
int len = trgurl.length();
System.out.println("string length is: " + trgurl.length());
System.out.println(trgurl.substring(n+6,len));
String find = "file:" +trgurl.substring(n+6,len);
System.out.println(find);
// mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(canvas1));
// mediaPlayer.release();
playerCmpt.getMediaPlayer().playMedia(find);
// mediaPlayer.stop();
// mediaPlayer.prepareMedia(find);
// mediaPlayer.stop();
//mediaPlayer.prepareMedia(find);
//JScrollPane scrollableTextArea = new JScrollPane(jPanel2);
//scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
}
}
});
});
JPanel playerPanel = new JPanel(new BorderLayout());
playerPanel.add(playerCmpt);
JSplitPane mainSplit = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
leftPane, playerPanel);
playerPanel.setMinimumSize(new Dimension(10, 10));
this.add(mainSplit);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//playerCmpt.getMediaPlayer().playMedia("D:\\test\\192.168.2.201_01_20180124_153000.avi");
}
public static void main(String[] args) {
new MyTestClass();
}
}

java jlabel working in windows but not in linux showing old, formats on screen, openjdk?

So I have written a Java application, that provides a transparent Heads up display at the top of the screen, it works perfectly on windows, but on my kubuntu 16.04 machine it does not clear the old label when you change the labels text, you end up with a ton of overlapping mess.
because a picture is worth a thousand words, the top is how it looks in windows, the bottom is how it looks under kubuntu:
https://s23.postimg.org/yra0vvlvf/rawr.png
here is the code:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.net.URL;
import javax.swing.*;
import java.io.*;
public class spob extends JFrame implements WindowFocusListener
{
public spob()
{
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final TrayIcon trayIcon = new TrayIcon((new ImageIcon("icon.png", "trayicon")).getImage());
final SystemTray tray = SystemTray.getSystemTray();
trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("spO2 pr monitor");
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}
setType(javax.swing.JFrame.Type.UTILITY);
setUndecorated(true);
getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
setSize(400, 35);
JLabel label = new JLabel("Loading...");
label.setFont(new Font("Tahoma", Font.BOLD, 28));
label.setForeground(Color.GREEN);
add(label);
setLocation(800, 0);
addWindowFocusListener(this);
setAlwaysOnTop( true );
this.setFocusable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
URL url = null;
BufferedReader in = null;
String[] anArray = new String[10];
anArray[0] = "<html><font color=green>- spO2:91 pr:65</font></html>";
anArray[1] = "<html><font color=red>+ spO2:85 pr:77</font></html>";
anArray[2] = "<html><font color=green>- spO2:90 pr:68</font></html>";
anArray[3] = "<html><font color=orange>+ spO2:89 pr:76</font></html>";
anArray[4] = "<html><font color=orange>- spO2:89 pr:72</font></html>";
anArray[5] = "<html><font color=orange>+ spO2:88 pr:73</font></html>";
anArray[6] = "<html><font color=red>- spO2:87 pr:78</font></html>";
anArray[7] = "<html><font color=red>+ spO2:86 pr:73</font></html>";
anArray[8] = "<html><font color=green>- spO2:92 pr:74</font></html>";
anArray[9] = "<html><font color=green>+ spO2:90 pr:71</font></html>";
while (true){
try {
Thread.sleep(200);
//url = new URL("http://192.168.1.153/stat.php");
//in = new BufferedReader(new InputStreamReader(url.openStream()));
//label.setText(in.readLine().toString());
Random randomno = new Random();
label.setText(anArray[randomno.nextInt(9 - 1) + 1]);
} catch (Exception ex) {
} finally {
//try {
// in.close();
//} catch (IOException e) {
//}
}
}
}
public void windowGainedFocus(WindowEvent e){}
public void windowLostFocus(WindowEvent e)
{
if(e.getNewState()!=e.WINDOW_CLOSED){
setAlwaysOnTop(false);
setAlwaysOnTop(true);
}
}
public static void main(String[] args)
{
new spob();
}
}
So, a number of issues
You're violating the single threaded rules of Swing, essentially, updating the UI from outside the context of the EDT, this can cause issues if the system is trying to paint something while you're trying to update it
getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f)); - Swing doesn't know how to deal with opaque components which have an alpha based color, it tends to not to update the any of the components beneath it.
Transparent windows are ... fun ... they tend to introduce their own issues beyond what we would normally expect.
On my Mac system I was able to reproduce the issue, but inconsistently. This was especially apparent, because the Mac OS keeps rendering a shadow around the text.
The first thing I got rid of was setType(javax.swing.JFrame.Type.UTILITY);, I also added a repaint request of the label's parent container which seems to have solved the symptoms of the problem, but again, I was able to execute the code without at times.
If you want to update the UI periodically, you should use a Swing Timer, see How to use Swing Timers for more details. If you need to do something in the background and then update the UI, you should use a SwingWorker, have a look Worker Threads and SwingWorker for more details
(wow is me, it doesn't like my animated gif :()
The example deliberately uses a translucent background, it's intended to show the frame. Change pane.setAlpha(0.5f); to pane.setAlpha(0.0f); to make it fully transparent (I've tested that as well).
If you have issues, uncomment the line label.getParent().repaint(); in the Timer and see if that helps
public class Test {
public static void main(String[] args) {
new Test();
}
private JLabel label;
private String[] anArray = {
"<html><font color=green>- spO2:91 pr:65</font></html>",
"<html><font color=red>+ spO2:85 pr:77</font></html>",
"<html><font color=green>- spO2:90 pr:68</font></html>",
"<html><font color=orange>+ spO2:89 pr:76</font></html>",
"<html><font color=orange>- spO2:89 pr:72</font></html>",
"<html><font color=orange>+ spO2:88 pr:73</font></html>",
"<html><font color=red>- spO2:87 pr:78</font></html>",
"<html><font color=red>+ spO2:86 pr:73</font></html>",
"<html><font color=green>- spO2:92 pr:74</font></html>",
"<html><font color=green>+ spO2:90 pr:71</font></html>"
};
private Random randomno = new Random();
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setAlwaysOnTop(true);
// Transparent window...
frame.setBackground(new Color(255, 255, 255, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BackgroundPane pane = new BackgroundPane();
// Set this to 0.0f to make it fully transparent
pane.setAlpha(0.5f);
pane.setLayout(new BorderLayout());
pane.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.setContentPane(pane);
label = new JLabel("Loading...");
label.setFont(new Font("Tahoma", Font.BOLD, 28));
label.setForeground(Color.GREEN);
frame.add(label);
frame.pack();
Dimension size = frame.getSize();
size.width = 400;
frame.setSize(size);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(anArray[randomno.nextInt(9 - 1) + 1]);
// label.getParent().repaint();
}
});
timer.start();
}
});
}
public class BackgroundPane extends JPanel {
private float alpha;
public BackgroundPane() {
setOpaque(false);
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
public float getAlpha() {
return alpha;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
}
}
nb I'm not using openJDK, I'm using Java 8, that might make a difference
Testing for capabilities
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
public class Test {
public static void main(String[] args) {
GraphicsEnvironment ge
= GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
boolean isUniformTranslucencySupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT);
boolean isPerPixelTranslucencySupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT);
boolean isShapedWindowSupported
= gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT);
System.out.println("isUniformTranslucencySupported = " + isUniformTranslucencySupported);
System.out.println("isPerPixelTranslucencySupported = " + isPerPixelTranslucencySupported);
System.out.println("isShapedWindowSupported = " + isShapedWindowSupported);
}
}

Getting null / empty JtextArea

I crated a Frame which have a panel inside it and the panel have a textarea inside it. Now i created a constructor which makes the frame visible for some time and after that it is set as invisible. Time for which it is visible it shows some massage.
When i run the constructor code inside the main method of outputDisplay class it shows the text massage
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
public class OutputDisplay {
static JFrame frame;
JPanel panel;
JTextArea area;
Font font;
public void timer(int time){
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
}
});
timer.start();
timer.setRepeats(false);
}
OutputDisplay(String ip,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.RED);
area.setSize(200, 200);
int j=0;
String[] t = {ip};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue,String path,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.MAGENTA);
area.setSize(200, 200);
int j=0;
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(500, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
OutputDisplay(String dialogue) throws InterruptedException{
frame = new JFrame("Report");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.BLUE);
area.setSize(200, 200);
String[] t = {dialogue};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 600);
frame.setVisible(true);
frame.setResizable(false);
}//constructor
public OutputDisplay() {
}//no arg
public void dialogue (String massage) throws InterruptedException{
frame = new JFrame("Massage");
frame.setLocation(400, 220);
JPanel panel = new JPanel();
JTextArea area = new JTextArea();
Font font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.GREEN);
area.setSize(200, 200);
int j=0;
String[] t = {massage};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(400, 100);
frame.setVisible(true);
Thread.sleep(8*1000);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//dialogue
static void warningPopUp (String massage){
JOptionPane.showMessageDialog(null, massage);
}//dialogue
public static void main(String[] args){
new OutputDisplay("We are checking for account validation"+"\n"
+ "If user id and password matches then we will goto websites for updation. " +"\n"
+ "You will get a complete report once we are done", 4*1000);
}//main
}//OutputDisplay
Don't call Thread.sleep(...) on the Swing EDT as that just puts your whole GUI to sleep.
Do use a Swing Timer instead.
Do Google and search this site for similar questions.
Please check out Lesson: Concurrency in Swing
Also check out the Swing Tutorials
Edit
You're still using Thread.sleep, again you shouldn't use it, but instead should use a Timer. Also, never set a JTextArea's size or preferred size ever. Do this and the scrollbars of your JScrollPane won't work. Instead, set its rows and columns.
import java.awt.Color;
import java.awt.Font;
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TimeLimitedDialogTester {
private static final int EB_GAP = 25;
private JPanel mainPanel = new JPanel();
public TimeLimitedDialogTester() {
mainPanel.add(new JButton(new ShowDialogAction("Show Dialog")));
mainPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, 2 * EB_GAP, 2 * EB_GAP, 2 * EB_GAP));
}
public JPanel getMainPanel() {
return mainPanel;
}
#SuppressWarnings("serial")
private class ShowDialogAction extends AbstractAction {
public ShowDialogAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Window mainWin = SwingUtilities.getWindowAncestor(mainPanel);
int seconds = 5;
String dialogTitle = "WARNING";
String text = "We are checking for account validation. If user id and password matches then we"
+ " will go to websites for updating. You will get a complete report once we are done.";
TimeLimitedDialog timeLimitedDialog = new TimeLimitedDialog(mainWin, seconds, dialogTitle, text);
timeLimitedDialog.dialogShow();
}
}
private static void createAndShowGui() {
TimeLimitedDialogTester timeLimitedDialog = new TimeLimitedDialogTester();
JFrame frame = new JFrame("TimeLimitedDialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(timeLimitedDialog.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class TimeLimitedDialog {
private static final int ROWS = 6;
private static final int COLS = 30;
private static final Color FG = Color.green.darker().darker();
private JDialog dialog;
private JTextArea displayArea = new JTextArea(ROWS, COLS);
private int seconds;
public TimeLimitedDialog(Window mainWin, int seconds, String dialogTitle, String text) {
displayArea.setWrapStyleWord(true);
displayArea.setLineWrap(true);
displayArea.setFocusable(false);
displayArea.setText(text);
displayArea.setForeground(FG);
displayArea.setFont(displayArea.getFont().deriveFont(Font.BOLD));
this.seconds = seconds;
dialog = new JDialog(mainWin, dialogTitle, ModalityType.APPLICATION_MODAL);
dialog.add(new JScrollPane(displayArea));
dialog.pack();
dialog.setLocationRelativeTo(mainWin);
}
public void dialogShow() {
new Timer(seconds * 1000, new TimerListener()).start();
dialog.setVisible(true);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (dialog != null && dialog.isVisible()) {
dialog.dispose();
}
((Timer) e.getSource()).stop();
}
}
}

Gui - JPanel adding JComponent into GridLayout cell

I'm trying to display a frame using GridLayout, but one of my panels isn't displaying.
The JPanel that I'm having trouble with (gridPanel) is supposed to have a 50 by 50 GridLayout and each cell in that grid is supposed to have a Square object added to it. Then that panel is supposed to be added to the frame, but it doesn't display.
import java.awt.*;
import javax.swing.*;
public class Gui extends JFrame{
JPanel buttonPanel, populationPanel, velocityPanel, gridPanel;
JButton setupButton, stepButton, goButton;
JLabel populationLabel, velocityLabel;
JSlider populationSlider, velocitySlider;
Square [] [] square;
public Gui() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Set up JButtons
buttonPanel = new JPanel();
setupButton = new JButton("Setup");
stepButton = new JButton("Step");
goButton = new JButton("Go");
buttonPanel.add(setupButton);
buttonPanel.add(stepButton);
buttonPanel.add(goButton);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2; //2 columns wide
add(buttonPanel, c);
//Set up populationPanel
populationPanel = new JPanel();
populationLabel = new JLabel("Population");
populationSlider = new JSlider(JSlider.HORIZONTAL,0, 200, 1);
populationPanel.add(populationLabel);
populationPanel.add(populationSlider);
c.fill = GridBagConstraints.LAST_LINE_END;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2; //2 columns wide
add(populationPanel, c);
//Set up velocityPanel
velocityPanel = new JPanel();
velocityLabel = new JLabel(" Velocity");
velocitySlider = new JSlider(JSlider.HORIZONTAL,0, 200, 1);
velocityPanel.add(velocityLabel);
velocityPanel.add(velocitySlider);
c.fill = GridBagConstraints.LAST_LINE_END;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2; //2 columns wide
add(velocityPanel, c);
//Set up gridPanel
JPanel gridPanel = new JPanel(new GridLayout(50, 50));
square = new Square[50][50];
for(int i = 0; i < 50; i++){
for(int j = 0; j < 50; j++){
square[i][j] = new Square();
gridPanel.add(square[i][j]);
}
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2; //2 columns wide
add(gridPanel, c);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
Gui frame = new Gui();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Square class
import java.awt.*;
import javax.swing.*;
public class Square extends JComponent{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(10, 10, 10, 10);
}
}
The reason you are not seeing anything are two-fold (though not entirely sure if the second is intentional, guessing on that part :)
JComponent is a bare-bone container, it has no ui delegate and no inherent size - it's up to your code to return something reasonable for min/max/pref
the painting rect is hard-coded to "somewhere" inside, which might or might be inside the actual component area
Following is showing (border just to see the boundaries)
public static class Square extends JComponent {
public Square() {
setBorder(BorderFactory.createLineBorder(Color.RED));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
#Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
#Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
}

Why does part of my RichJLabel text look covered/hidden?

I've been reading the Swing Hacks book and have used some of their code for the RichJLabel part. I understand what the code does, but not why some of the word is covered or looks hidden. It's not that it's not drawing all of the text because even half of the 'a' in horizontal is missing.
//imported libraries for the GUI
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.*;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.*;
//Rich JLabel
import java.awt.GraphicsEnvironment;
import java.awt.Graphics2D;
import java.awt.FontMetrics;
import java.awt.RenderingHints;
import java.awt.font.*;
import javax.swing.ListSelectionModel;
import java.awt.Color;
import java.awt.Font;
public class nameInterfaceOne
{
//Declared components
static JFrame frame;
static JPanel TotalGUI, northP, southP, eastP, centerP, westP;
static JButton buttons;
//Frame method
public nameInterfaceOne()
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} //For a different look & feel, change the text in the speech marks
catch (ClassNotFoundException e) {}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
catch (UnsupportedLookAndFeelException e) {}
frame = new JFrame("Interface");
frame.setExtendedState(frame.NORMAL);
frame.getContentPane().add(create_Content_Pane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500); //Size of main window
frame.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// gets & sets frame size/location
int fw = frame.getSize().width;
int fh = frame.getSize().height;
int fx = (dim.width-fw)/2;
int fy = (dim.height-fh)/2;
//moves the frame
frame.setLocation(fx, fy);
}
public JPanel create_Content_Pane()
{
TotalGUI = new JPanel();
TotalGUI.setLayout(new BorderLayout(5,5)); //set layout for the Container Pane
northP = new JPanel();
northP.setBorder(new TitledBorder(new EtchedBorder(), "Label"));
TotalGUI.add(northP, BorderLayout.NORTH);
RichJLabel label = new RichJLabel("Horizontal", 1);
label.setLeftShadow(1,1,Color.white);
label.setRightShadow(1,1,Color.gray);
label.setForeground(Color.black);
label.setFont(label.getFont().deriveFont(20f));
Box top = Box.createHorizontalBox();
top.add(Box.createHorizontalStrut(10));
top.add(label);
top.add(Box.createHorizontalStrut(10));
northP.add(top);
//EAST Panel
eastP = new JPanel();
eastP.setBorder(new TitledBorder(new EtchedBorder(), "Boxes"));
TotalGUI.add(eastP, BorderLayout.EAST);
Box right = Box.createVerticalBox();
right.add(Box.createVerticalStrut(20));
right.add(new JLabel("EAST SIDE!"));
eastP.add(right);
//WEST Panel
westP = new JPanel();
westP.setBorder(new TitledBorder(new EtchedBorder(), "Buttons"));
TotalGUI.add(westP, BorderLayout.WEST);
Box left = Box.createVerticalBox();
left.add(Box.createVerticalStrut(10));
ButtonGroup JbuttonGroup = new ButtonGroup();
JButton buttons;
JbuttonGroup.add(buttons = new JButton("One"));
buttons.setToolTipText("This is Button One");
left.add(buttons);
left.add(Box.createVerticalStrut(10));
JbuttonGroup.add(buttons = new JButton("Two"));
buttons.setToolTipText("This is Button Two");
left.add(buttons);
left.add(Box.createVerticalStrut(10));
JbuttonGroup.add(buttons = new JButton("Three"));
buttons.setToolTipText("This is Button Three");
left.add(buttons);
left.add(Box.createVerticalStrut(10));
westP.add(left);
TotalGUI.setOpaque(true);
return(TotalGUI);
}
//Main method calling a new object of
public static void main(String[] args)
{
new nameInterfaceOne();
}
}
//RICH JLABEL CLASS
class RichJLabel extends JLabel
{
private int tracking;
public RichJLabel(String text, int tracking) {
super(text);
this.tracking = tracking;
}
private int left_x, left_y, right_x, right_y;
private Color left_color, right_color;
public void setLeftShadow(int x, int y, Color color) {
left_x = x;
left_y = y;
left_color = color;
}
public void setRightShadow(int x, int y, Color color) {
right_x = x;
right_y = y;
right_color = color;
}
public Dimension getPreferredSize()
{
String text = getText();
FontMetrics fm = this.getFontMetrics(getFont());
int w = fm.stringWidth(text);
w += (text.length())*tracking;
w += left_x + right_x;
int h = fm.getHeight();
h += left_y + right_y;
return new Dimension(w,h);
}
public void paintComponent(Graphics g) {
((Graphics2D)g).setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
char[] chars = getText().toCharArray();
FontMetrics fm = this.getFontMetrics(getFont());
int h = fm.getAscent();
int x = 0;
for(int i=0; i<chars.length; i++)
{
char ch = chars[i];
int w = fm.charWidth(ch) + tracking;
g.setColor(left_color);
g.drawString(""+chars[i],x-left_x,h-left_y);
g.setColor(right_color);
g.drawString(""+chars[i],x+right_x,h+right_y);
g.setColor(this.getForeground());
g.drawString(""+chars[i],x,h);
x+=w;
}
((Graphics2D)g).setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
} // end paintComponent()
}
Thank you in advance for any help :)
Empirically, the problem disappears when adding the label directly to the (default) FlowLayout of northP.
northP.add(label);
Addendum: An alternative is to override getMaximumSize(), as suggested in How to Use BoxLayout: Specifying Component Sizes.
#Override
public Dimension getMaximumSize() {
return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
}