placing components in GridBagLayout - swing

I am trying to place the JLabel and JTextfield like this,
First Name Textbox -> First Name is a label named as lblFirstname
Last Name Textbox TextBox is JTextField
tried using GridBagLayout,
the constraints applied are,
lblFirstNameCons.gridx = 0;
lblLastNameCons.gridy = 0;
txtFirstName.gridx = 0;
txtLastNameCons.gridy = 3;
I am getting the output like this,
First NameTextbox -> There is no space and also, the JTextField is almost invisible.

The layout should be something like this. The values in parenthesis are the gridx and gridy (grix, gridy):
First Name (0, 0) Textbox (1, 0)
Last Name (0, 1) Textbox (1, 1)

You should make sure that the fill property of the GridBagConstraint is set to HORIZONTAL for the textfield and make sure that the weightx is set to something greater than 0
Or you can indicate to the textfield the desired number of columns to display (this will eventually influence the preferred size of the textfield).
Here is an example showing that:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestGridBagLayout {
protected void initUI() throws MalformedURLException {
final JFrame frame = new JFrame();
frame.setTitle(TestGridBagLayout.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridBagLayout());
JLabel firstName = new JLabel("First name:");
JLabel lastName = new JLabel("Last name:");
JTextField firstNameTF = new JTextField();
JTextField lastNameTF = new JTextField();
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(firstName, gbc);
gbc.weightx = 1;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(firstNameTF, gbc);
gbc.gridwidth = 1;
gbc.weightx = 0;
panel.add(lastName, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
panel.add(lastNameTF, gbc);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestGridBagLayout().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}

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

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

Why do the JButton in my dialog look weird

I'm fairly new to Java Swing/AWT et al and hence the question. I have a simple dialog with some text and a couple JButton. I am using the GridbagLayout for this dialog.
But when I look at the dialog, the JButtons are kind of having a weird shape and I cannot seem to right justify the text either.
Is this a limitation of the Layout I am using. Is there much simpler and elegant solution for my problem with either the buttons or the textlayout?
A screenshot of the dialog is attached below.
The code for my dialog Class is:
public class UpgradePopupWindow extends JPanel implements ActionListener {
static final long serialVersionUID = 0;
final String upgrade = " Continue Upgrade ";
final String restore = "Restore Previous Version";
JPanel panels;
JButton upgradeButton;
JButton restoreButton;
JTextArea Message;
JFrame newFrame;
FlasherThread flash;
protected JTextArea addText(String text, boolean visible, int fontStyle) {
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font("SansSerif", fontStyle, 12)); //$NON-NLS-1$
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setBackground(Color.DARK_GRAY);
textArea.setForeground(Color.WHITE);
textArea.setOpaque(false);
textArea.setVisible(visible);
textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
add(textArea);
return textArea;
}
protected JTextArea addMultiLineLabel(String text, int fontStyle, int fontSize, Object constraints) {
JTextArea textArea = new JTextArea(text);
textArea.setFont(new Font("SansSerif", fontStyle, fontSize));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setBackground(new Color(0, 0, 0, 0)); // Zero alpha = transparent background
textArea.setOpaque(false);
textArea.setBorder(new TitledBorder(""));
textArea.setAlignmentX(Component.CENTER_ALIGNMENT);
add(textArea, constraints);
return textArea;
}
private UpgradePopupWindow(JFrame frame, Object ft) {
super(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
flash = (FlasherThread)ft;
String text = "An error occurred during the attempt to update your device's software. We recommend the following: (1) Restore your device to its previous version, (2) back up important data, and then (3) try updating your device again. If you continue with the current update, only your previously backed-up data will be available.";
//addFiller(5);
//addLabel(text, Font.PLAIN, 12);
gbc.gridy = 0;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
addMultiLineLabel(text, Font.PLAIN, 12, gbc);
//addText(text, true, Font.PLAIN);
addFiller(20);
newFrame = frame;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
upgradeButton = new JButton(upgrade);
upgradeButton.setActionCommand("upgrade");
upgradeButton.addActionListener(this);
upgradeButton.setEnabled(true);
upgradeButton.setBackground(Color.WHITE);
upgradeButton.setForeground(Color.GRAY);
add(upgradeButton,gbc);
++ gbc.gridx;
restoreButton = new JButton(restore);
restoreButton.setActionCommand("restore");
restoreButton.addActionListener(this);
restoreButton.setEnabled(true);
//restoreButton.setForeground(Color.DARK_GRAY);
restoreButton.setBackground(Color.DARK_GRAY);
add(restoreButton,gbc);
setOpaque(true);
newFrame.setContentPane(this);
//newFrame.getContentPane().setBackground(Color.LIGHT_GRAY);
}
protected void addFiller(int size) {
Dimension diminsion = new Dimension(size, size);
Filler filler = new Filler(diminsion, diminsion, diminsion);
filler.setAlignmentX(Component.CENTER_ALIGNMENT);
add(filler);
}
public static void createGUI(Object obj) {
//Create and set up the frame.
JFrame frame = new JFrame("PopUp Dialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(440, 180));
//create and setup the content pane
UpgradePopupWindow popUpContentPane = new UpgradePopupWindow(frame, obj);
popUpContentPane.setOpaque(true);
frame.setContentPane(popUpContentPane);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if("restore".equals(e.getActionCommand())) {
System.out.println("restore button selected");
flash.setUpgradeRestoreChoice("restore");
newFrame.dispose();
} else if ("upgrade".equals(e.getActionCommand())) {
System.out.println("upgrade button selected");
flash.setUpgradeRestoreChoice("upgrade");
newFrame.dispose();
}
}
}
![alt text][1]
As #Javaguru said - use MigLayout. For the text DO NOT use JTextArea. This component is mostly for text editing. JLabel is enough for your purpose - you can even use HTML inside of it.
You don't have to create this kind of dialog from scratch. There are many options. One of them is my Swing TaskDialog framework ;)
But if you still insist on implementing it yourself here a simple implementation using MigLayout ( even with MigLayout it can be done using several differnt ways):
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
public class TestDialog extends JDialog {
private static final long serialVersionUID = 1L;
private final JLabel label = new JLabel("Your text here");
private final JButton restoreButton = new JButton("Restore Previous Version");
private final JButton ugradeButton = new JButton("Continue Upgrade");
public TestDialog( String title ) {
super( (JDialog)null, title );
setContentPane(createContent());
}
private JPanel createContent() {
JPanel content = new JPanel();
content.setPreferredSize( new Dimension(400, 100));
content.setBackground(Color.WHITE);
content.setLayout(new MigLayout("", "[400px,grow][pref!]", "[grow][pref!]"));
this.label.setVerticalAlignment(SwingConstants.TOP);
content.add(this.label, "cell 0 0 2 1,grow");
content.add(this.restoreButton, "cell 1 1,alignx left,aligny top");
content.add(this.ugradeButton, "cell 0 1,alignx right,aligny top");
return content;
}
// very simplified test
public static void main(String[] args) {
TestDialog dlg = new TestDialog("Popup Dialog");
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.pack();
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);
}
}
There are a lot of much more elegant solutions out there .. ;)
You should really never use GridbagLayout if not absolutely required (or only with a gui editor)! It's simply a pain in the ass!
Rather I suggest using one of the following LayoutManagers:
MigLayout: http://www.miglayout.com/
TableLayout: https://tablelayout.dev.java.net/
Creating a pleasing layout is much simpler and intuitive than with the GridbagLayout and its configuration overhead.