Getting null / empty JtextArea - swing

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

Related

List app in java cant call to a function. pls

I have done all the details I have done, and I don't get an error but what I want to do doesn't work.
I tried to check on google, chatgpt, and friends. I was expected to a window with wait for input from the user, and the user writes a task and he enters "submit". Then, a window of DeadLine comes with an import calendar. So, the user chooses a DeadLine and he presses "OK". and then I created a constructor with the selected time and the task (to print the input) therefore, I called to the constructor and its doesn't call. Please help me. ):
The code:
import javax.swing.*;
import com.toedter.calendar.JCalendar;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.Date;
public class List extends JFrame {
String todo = "TO DO: ";
ImageIcon icon1;
JButton button;
public static String task;
static JLabel label,label2,label3;
static JLabel titletaskLabel,titletaskLabel2,titletaskLabel3,titletaskLabel4;
static JFrame frame;
public static JTextField text;
static Font myFont = new Font("Ink Free", Font.BOLD, 30);
static Font yourFont = new Font("Ink Free", Font.HANGING_BASELINE, 20);
static JCalendar calendar;
static Date selectedDate;
List() {
frame = new JFrame("List");
icon1 = new ImageIcon("list.png");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 900);
frame.setIconImage(icon1.getImage());
frame.setLayout(null);
label = new JLabel("To Do List: ");
label.setBounds(50, 50, 200, 20);
label2 = new JLabel("Enter a task: ");
label2.setFont(myFont);
label2.setBounds(70, 460, 200, 40);
button = new JButton("Submit");
button.setBounds(470, 500, 80, 50);
button.setBackground(Color.green);
button.addActionListener(new ActionListener1());
text = new JTextField();
text.setBounds(70, 500, 370, 50);
text.setFont(myFont);
frame.add(text);
frame.add(button);
frame.add(label);
frame.add(label2);
frame.setVisible(true);
}
static void addDeadline() {
JDialog dialog = new JDialog(frame, "Choose a Due Date", true);
dialog.setSize(400, 400);
dialog.setLocationRelativeTo(frame);
JPanel calendarPanel = new JPanel();
calendarPanel.setBounds(70, 600, 370, 200);
calendar = new JCalendar();
calendarPanel.add(calendar);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get the selected date
Calendar selectedCalendar = calendar.getCalendar();
selectedDate = selectedCalendar.getTime();
task = text.getText();
System.out.println(selectedDate);
dialog.setVisible(false);
tasks(); // add the new task to the frame
}
});
calendarPanel.add(okButton);
dialog.add(calendarPanel);
dialog.setVisible(true);
}
static void tasks() {
titletaskLabel = new JLabel(task + "The DeadLine is: " + selectedDate);
titletaskLabel.setBounds(50, 70, 200, 50);
frame.add(titletaskLabel);
}
static class ActionListener1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
addDeadline();
}
}
}
public class Main extends List{
public static void main(String[] args) {
new List();
}
}

How to set label text to JTextField input

I'm trying to get a user to input a name in one panel on CardLayout and for the input to then define a JLabels text in the next panel that it switches to. I used System.out.println(userName); to double check that it was picking up the text and it definitely is but I don't know how to get the 'user' text to be that of the JTextFields input.
Full working code below:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class gameDataPanel {
private JFrame frame = new JFrame("Game Data Input");
private JPanel mainPanel, loginPanel, gameDataPanel;
private JLabel playerName, user;
private JTextField playerNameInput;
private JButton submit;
private CardLayout gameDataLayout = new CardLayout();
private String userName;
public gameDataPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(gameDataLayout);
playerName = new JLabel("Enter Player Name: ");
playerNameInput = new JTextField(30);
submit = new JButton("Submit");
loginPanel = new JPanel();
loginPanel.add(playerName);
loginPanel.add(playerNameInput);
loginPanel.add(submit);
gameDataPanel = new JPanel();
user = new JLabel();
user.setText(userName);
gameDataPanel.add(user);
mainPanel.add(loginPanel, "1");
mainPanel.add(gameDataPanel, "2");
gameDataLayout.show(mainPanel, "1");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
playerNameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
frame.add(mainPanel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
gameDataPanel gd = new gameDataPanel();
}
}
Thanks
I am not 100% sure, whether i understood you correctly: You want to display the users name, which is entered in "playerNameInput" to be displayed in the JLabel "user" ? In this case, you have to update your JLabel object in your event listener AFTER the user entered something and pressed the push button. Try something like this:
playerNameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
user.setText(userName);
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
I hope this helps :-)

Unable to Switch JPanels after loading jcef browser window

I am trying to use jcef browser inside my swing application but getting problems.
First of all i unable to add jcef browser as JPanel component on jFrame. Then i try to add directly on jframe
[code]getContentPane().add(browser.getUIComponent(), BorderLayout.CENTER);[/code]
Now when browser window load inside JFrame, and If i want to switch with other Jpanel then it is not working working in any way
I cant switch the screen after loading CEF browser. Can any one point out what i need to do. Here is my test jframe.
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.browser.CefBrowser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class CardLayoutTst extends JFrame {
static CefBrowser browser = null;
static CefClient client = null;
private static final long serialVersionUID = 1L;
private JPanel cardPanel, jp1, jp2, buttonPanel;
private JLabel jl1, jl2;
private JButton btn1, btn2;
private CardLayout cardLayout = new CardLayout();
public CardLayoutTst() {
setTitle("Test med CardLayout");
setSize(400, 300);
cardPanel = new JPanel();
buttonPanel = new JPanel();
cardPanel.setLayout(cardLayout);
jp1 = new JPanel();
jp2 = new JPanel();
jl1 = new JLabel("Card 1");
jl2 = new JLabel("Card 2");
jp1.add(jl1);
jp2.add(jl2);
cardPanel.add(jp1, "1");
cardPanel.add(browser.getUIComponent(), "2");
btn1 = new JButton("Show Card 1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "1");
}
});
btn2 = new JButton("Show Card 2");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "2");
}
});
buttonPanel.add(btn1);
buttonPanel.add(btn2);
add(cardPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
CefApp.getInstance().dispose();
dispose();
}
});
}
public static void main(String[] args) {
client = CefApp.getInstance().createClient();
browser = client.createBrowser("http://www.google.com", false, false);
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CardLayoutTst frame = new CardLayoutTst();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
It is a bit late but I had just the same problem. A friend of mine solved the issue.
You have to create CefSettings, set the windowless_rendering_enabled to false and pass this settings object to the getInstance call:
CefSettings settings = new CefSettings();
settings.windowless_rendering_enabled = false;
client = CefApp.getInstance(settings).createClient();

Margins with LineBorders

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

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