Java Swing GUI, customising JtabbedPane style - java

I am a beginner in swing. I tried to create a tabbed window as part of the GUI for my project. But as shown below, the buttons for navigating tabs shows some sort of a border. Is there a way I can remove these borders? See the attached image to see the problem.
The code for the GUI is as follows
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class tst {
/**
* #param args the command line arguments
*/
public static String generateHtml(String tabButtonLabel,String style) {
/*##Generates HTML for the tab button when the button label is given*/
String ret = "<html><body style = '"+style+"'>"+tabButtonLabel+"</body></html>";
return ret;
}
public static void main(String[] args) {
// TODO code application logic here
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JFrame frame = new JFrame("tst");
frame.setVisible(true);
frame.setSize(screenSize);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*Groups tab*/
JPanel groups = new JPanel();
groups.setBackground(Color.gray);
/*Settings Tab*/
JPanel settings = new JPanel();
/*About Tab*/
JPanel about = new JPanel();
/*Tabbed pane to hold all panels*/
JTabbedPane tabbedPane = new JTabbedPane();
/*Tabbed Pane CSS*/
String tabButtonCss = "margin:0;width:110px;height:10px;border-radius:3px;padding:10px;background:#fff;text-align:center;border:none;";
tabbedPane.setVisible(true);
tabbedPane.add(generateHtml("Groups",tabButtonCss),groups);
tabbedPane.add("Settings",settings);
tabbedPane.add("About",about);
/*Tab styles*/
tabbedPane.setBackground(Color.gray);
tabbedPane.setForeground(Color.white);
tabbedPane.setBounds(0, 0, 0,0);
//tabbedPane.setBorder(new EmptyBorder(-10,-20,-10,0));
frame.add(tabbedPane);
}
}

As noted by #Smit, it is all down to the CSS. Note also that the Java HTML/CSS engine does not recognize the '3 digit' style shortcut of #fff for colors. To get white we must use #ffffff.
import java.awt.*;
import javax.swing.*;
class ExampleCSS {
public static void showStyle(String style) {
JPanel gui = new JPanel(new BorderLayout());
String html1 = "<html><body style = '"+style+"'>";
String html2 = "</body></html>";
JTabbedPane tp = new JTabbedPane();
tp.addTab(html1 + "Groups" + html2, new JLabel(style));
tp.addTab(html1 + "Settings" + html2, new JLabel(style));
tp.addTab(html1 + "About" + html2, new JLabel(style));
gui.add(tp);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(gui);
f.setMinimumSize(new Dimension(400,100));
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
String[] css = {
"margin:0;background:#ffffff;",
"padding:10px;",
"width:110px;height:10px;border-radius:3px;"
+ "text-align:center;border:none;"
};
showStyle(css[0]);
showStyle(css[0]+css[1]);
showStyle(css[0]+css[1]+css[2]);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
See also #whiskeyspider suggestion re #trashgod solution for the BG color. Much (much) nicer than trying to force it in the HTML.

Related

Java FlowLayout

I am writing some Java code that allows the user to see a frame with JLabel, JTextField and JButton.
I want the JLabel to be called "Count" and I have a problem with FlowLayout.
I want the interface to look like this:
Instead, I have this:
This is my code:
package modul1_Interfate_Grafice;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Exercitiu04 implements ActionListener {
private JFrame frame;
private JLabel labelCount;
private JTextField tfCount;
private JButton buttonCount;
private int count = 0;
public void go() {
frame = new JFrame("Java Counter");
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
frame.getContentPane().add(BorderLayout.CENTER, labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
labelCount.add(tfCount);
buttonCount = new JButton("Count");
labelCount.add(buttonCount);
buttonCount.addActionListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 150);
frame.setLocation(400, 200);
}
#Override
public void actionPerformed(ActionEvent event) {
count++;
tfCount.setText(count + "");
}
public static void main(String[] args) {
Exercitiu04 a = new Exercitiu04();
a.go();
}
}
Solve it.
Instead of labelCount.setLayout(new FlowLayout());` i should have had
frame.setLayout(new FlowLayout());
From description of JLabel class,
JLabel is:
A display area for a short text string or an image, or both.
But here: labelCount.add(tfCount) and here labelCount.add(buttonCount) you're trying to put a textfield and a button into a label. In this case, positions of button and textfield are controlled by FlowLayout but position of the text in the label is not.
Instead of this, you should put all of your elements in common JPanel, like this:
...
frame = new JFrame("Java Counter");
frame.setLayout(new BorderLayout());
JPanel wrapper = new JPanel(); // JPanel has FlowLayout by default
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
wrapper.add(labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
wrapper.add(tfCount);
buttonCount = new JButton("Count");
buttonCount.addActionListener(this);
wrapper.add(buttonCount);
frame.add(BorderLayout.CENTER, wrapper);
...
And, like MasterBlaster said, you should put swing methods in EDT.
There are only two things you should know about FlowLayout:
a) It is a default layout manager of the JPanel component
b) It is good for nothing.
This trivial layout cannot be achieved with FlowLayout.
When doing layouts in Swing, you should familiarize yourself
with some powerful layout managers. I recommend MigLayout and
GroupLayout.
package com.zetcode;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
Simple UI with a MigLayout manager.
Author Jan Bodnar
Website zetcode.com
*/
public class MigLayoutCounterEx extends JFrame {
public MigLayoutCounterEx() {
initUI();
}
private void initUI() {
JLabel lbl = new JLabel("Counter");
JTextField field = new JTextField(10);
JButton btn = new JButton("Count");
createLayout(lbl, field, btn);
setTitle("Java Counter");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout());
add(arg[0]);
add(arg[1]);
add(arg[2]);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCounterEx ex = new MigLayoutCounterEx();
ex.setVisible(true);
});
}
}
The example is trivial. You just put the three components into the
cells.
Screenshot:
You shouldn't use setSize when dealing with FlowLayout. Instead use pack(). It makes the window just about big enough to fit all your components in. That should tidy things up for you

frame.getContentPane().add(); not working properly?

I've been having some (very annoying) trouble with these scripts that I've created.
Sburb.java
import java.awt.Color;
import javax.swing.*;
public class Sburb
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Welcome to Sburb");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
spirograph page = new spirograph();
progressbar bar = new progressbar();
frame.getContentPane().add(page);
frame.getContentPane().add(bar);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
}
progressbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class progressbar extends JPanel
{
JProgressBar current;
JTextArea out;
JButton find;
Thread runner;
int num = 1;
progressbar()
{
super();
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
current = new JProgressBar(0, 2000);
current.setStringPainted(false);
pane.add(current);
//setContentPane(pane);
}
public void iterate() {
while (num < 2000) {
current.setValue(num);
try {
Thread.sleep(300);
} catch (InterruptedException e) { }
num += 5;
}
}
// public static void main(String[] arguments) {
// progressbar frame = new progressbar();
// frame.pack();
// frame.setVisible(true);
// frame.iterate();
// }
}
spirograph.java
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class spirograph extends JPanel
{
private ImageIcon image;
private JLabel label;
private JLabel frame = new JLabel();
private JPanel panel = new JPanel();
spirograph()
{
this.setOpaque(true);
this.setBackground(Color.BLACK);
setLayout(new FlowLayout());
image = new ImageIcon(getClass().getResource("Gate.gif"));
label = new JLabel(image);
add(label);
progressbar bar = new progressbar();
}
}
I'm trying to call the file "progressbar" to the Sburb file but when I do, it gives me just the simple JFrame of this (not fixed):
http://imgur.com/1aAmPwJ
And when I get rid of the "frame.getContentPane().add(bar);" in Sburb.java, it gives me this (fixed, kind-of):
http://imgur.com/15aGtT2
How do I fix this? I've looked everywhere and yet I still can't figure it out! I also can't seem to figure out how to align the bar directly below the gif.
frame.getContentPane().add(page);
frame.getContentPane().add(bar);
The content pane of a JFrame is a set to a BorderLayout which can only accept one component in any one of the border layout constraints. Given no constraints were supplied here, the JRE will try to put them both in the CENTER.
For this, and a variety of other reasons, I would advise to ignore the existing content pane, arrange the entire GUI (as many panels as it consists of) into another panel (let's call it ui) then call
frame.setContentPane(ui);

Why is my JFrame image not changing the icon?

I am trying to change the image icon on a JFrame and it is not showing up. I have tried both the absolute path to my desktop and then the path that I have in Eclipse. Why is this not working. I have looked on stackoverflow and this is how it looks like that it is probably done, but for some reason the code below is not working.
code:
package TestMenu;
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TestJFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public TestJFrame() {
ImageIcon img = new ImageIcon("C:\\Users\\itpr13266\\workspace\\TestMenu\\src\\TestMenu\\img\\s.jpg");
setIconImage(img.getImage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(117, 105, 10, 10);
contentPane.add(panel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestJFrame frame = new TestJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
No exception was thrown.
The code is fix now. I had the wrong image format type.
Code that does not work:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
public class MenuLookDemo {
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
menuBar = new JMenuBar();
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(menuItem);
ImageIcon icon = createImageIcon("src\\TestMenu\\img\\stop.jpg");
menuItem = new JMenuItem("Both text and icon", icon);
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(icon);
menuItem.setMnemonic(KeyEvent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
menuBar.add(menu);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = MenuLookDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* 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.
JFrame frame = new JFrame("MenuLookDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
MenuLookDemo demo = new MenuLookDemo();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(450, 260);
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();
}
});
}
}
Error: (From the above example and it is just like the example above which I got to work)
Couldn't find file: src\TestMenu\img\stop.jpg
May be that BMP is not supported. If you follow the Java source code from the constructor of ImageIcon you end up at:
(java.awt.Toolkit.java)
/**
* Returns an image which gets pixel data from the specified file,
* whose format can be either GIF, JPEG or PNG.
* ...
*/
public abstract Image getImage(String filename);
According to this article, ImageIcon supports GIF, JPEG, or PNG. Try converting your image to another format using something like GIMP or Paint and see if you get the same results.
http://docs.oracle.com/javase/7/docs/api/java/awt/Toolkit.html#getImage%28java.lang.String%29
It worked for me, I substituted a jpeg on my c drive and changed the path accordingly. It placed the icon in the upper left corner of the frame. Try simplifying your path to C:\filename and see if it works.
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Swing {
public static void main(String[] args) {
////jframe = a GUI(graphical user interface) window to add components
JFrame frame = new JFrame();//we are creating a new frame
frame.setVisible(true);//this helps to make the frame visible
frame.setSize(500, 500);//this is for resizing our window into any size
frame.setTitle("Manoj sai");//to set the title for the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//normally when we hit X button it will hide but it will not close so to close that we have to give that when we press X exit_on_close
frame.setResizable(false);//this makes the window not resizeable we cant resize the window
//ImageIcon will help to keep images in GUI(its a separate class)
ImageIcon image = new ImageIcon("C:\\Users\\manoj\\Pictures\\logos\\logo.jpg");//creates an image icon
frame.setIconImage(image.getImage());//sets the selected image for icon for our window
}
}
here use the file path which is in your computer then u will get ur icon displayed after importing to the eclipse use the path which is in ur local disc c ex:"C:\\Users\\manoj\\Pictures\\logos\\logo.jpg"

JFrame to JApplet doesnt work in browser

I have a Java program with a Swing GUI im trying to make it work as a JApplet on a HTML file when I test it on Eclipse launch it as a Applet it works but when I compile it using javac. I get all these files Reverser.class, Reverser$1.class, Reverser$2.class, Reverser$3.class and Reverser$4.class. It doesnt work an help
<HTML>
<BODY>
<applet code="Reverser.class", height="500" width="800">
</applet>
</BODY>
</HTML>
package Applets;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Reverser extends JApplet
{
/**
*
*/
private static final long serialVersionUID = 1L;
//All Swing elements declared here
private JTextArea userinput, useroutput;
private JScrollPane sbr_userinput, sbr_useroutput;
private JButton runButton, clearButton, homeButton;
private String text; //User input stored here
private String reversed_text; //reversed text stored here
public void init()
{
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setContentPane(GUI());
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public Container GUI() //Main GUI container here
{
JPanel totalGUI = new JPanel(); //Main panel set here
totalGUI.setLayout(new GridLayout(1, 2, 3, 3)); //Main panel layout set here.
JPanel lPanel = new JPanel(); //Left panel made here
lPanel.setLayout(new GridLayout(2, 1, 3 , 3)); //Left panel layout set here
totalGUI.add(lPanel); // Left Panel added to main panel.
JPanel rPanel = new JPanel(new GridLayout(3, 1, 3 , 3)); //Right panel made here and its layout set here aswell
totalGUI.add(rPanel);//Right panel added to main panel.
//Userinput TextArea made here
userinput = new JTextArea("Welcome to wicky waky text reverser!!!" + "\n" + "Enter your sentence HERE man!!!!");
userinput.setEditable(true); //TextArea set to editable
userinput.setLineWrap(true);
userinput.setWrapStyleWord(true);
lPanel.add(userinput);//TextArea added to left panel
useroutput = new JTextArea(); //useroutput TextArea set here
useroutput.setEditable(false); //TextArea set to not editable
useroutput.setLineWrap(true);
useroutput.setWrapStyleWord(true);
lPanel.add(useroutput); //TextArea added to the left panel
//Scroll bar made here
sbr_userinput = new JScrollPane(userinput, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sbr_userinput.setPreferredSize(new Dimension(300, 300));
lPanel.add(sbr_userinput); //Scroll bar added to left panel
//Scroll bar made here
sbr_useroutput = new JScrollPane(useroutput, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sbr_useroutput.setPreferredSize(new Dimension(300, 300));
lPanel.add(sbr_useroutput); //Scroll bar added to the left panel
runButton = new JButton("RUN"); //Button made here
runButton.addActionListener(new ActionListener() //Action Listener made here
{
public void actionPerformed(ActionEvent e)
{
text = userinput.getText(); //Get userinput here
reversed_text = reverser(text); //reverser method called here
try {
userinput.setText("");
userinput.setText("Processed");
Thread.sleep(500); //sleep 0.5 sec
//Print out all output here
useroutput.setText("Your sentence is ==> " + text + "\n" + "\n"
+ "Your reversed sentence is ==> " + reversed_text);
} catch (InterruptedException e1)
{
e1.printStackTrace();
}
System.out.println("working");
}
});
rPanel.add(runButton); //Add button to right panel
clearButton = new JButton("CLEAR"); //New button made here
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
userinput.setText(""); //Set userinput to empty
useroutput.setText(""); //Set useroutput to empty
System.out.println("cleared");
}
});
rPanel.add(clearButton); //Add button to right panel
homeButton = new JButton("HOME"); //New button made here
homeButton.addActionListener(new ActionListener() //Action Listener added here
{
public void actionPerformed(ActionEvent e)
{
}
});
rPanel.add(homeButton); //add button to right panel
totalGUI.setOpaque(true);
return totalGUI; // return totalGUI
}
public static String reverser(String text)
{
//"text" is now put in the object "reverse_text", StringBuffer used so I can use the reverse method.
StringBuffer reverse_text = new StringBuffer(text);
String reversed = reverse_text.reverse().toString(); //reverse and toString methods used.
return reversed; // return revered
}
}
You don't have the package name in your applet. Consider changing
code="Reverser.class"
to
code="Applets.Reverser.class"
and making sure that the class file is in the Applets subdirectory relative to the HTML file. Or even better, create a jar file.
Also you need to post the error messages that the browser is giving you. You could have a version incompatibility for all we know.

change jlabel with method

I am writing a small program that converts files, and I wanted to have a box pop up that asks the user to please wait while the program loops through and converts all the relevant files, but I am running into a small problem. The box that pops up should have a JLabel and a JButton, while the user is "waiting" I wanted to display a message that says please wait, and a disabled "OK" JButton, and then when its finished I wanted to set the text of the JLabel to let them know that It successfully converted their files, and give them a count of how many files were converted. (I wrote a method called alert that sets the text of the label and enables the button.) The problem is That while the program is running, the box is empty, the Label and the Button are not visible, when it finishes, label appears with the final text that I want and the button appears enabled. I am not sure exactly what is going on, I tried changing the modifiers of the JLabel and JButton several times but I cant seem to get it to work correctly. Here is the code for the box that pops up, any help is greatly appricated.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends javax.swing.JFrame{
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel("Please Wait while I convert your files");
private static JButton OK = new JButton("OK");
public PleaseWait(){
// creates the main window //
JFrame mainWindow = new JFrame();
mainWindow.setTitle("Chill For A Sec");
mainWindow.setSize(width, height);
mainWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
mainWindow.add(mainLayout);
// sets everything visible //
mainWindow.setVisible(true);
}
public static void alert(){
OK.setEnabled(true);
String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + total + " files Converted");
}
}
Okay here's the issue. You are extending the JFrame . That means your class IS a JFrame.
When you create the PleaseWait frame you don't do anything to it. This is the empty box you are seeing. You are instead creating a different JFrame in your constructor. Remove your mainWindow and instead just use this. Now all of your components will be added to your PleaseWait object. That should fix your blank box issue.
You need an application to create your frame first. This is a simple example of such application.
import javax.swing.UIManager;
import java.awt.*;
public class Application {
boolean packFrame = false;
//Construct the application
public Application() {
PleaseWait frame = new PleaseWait();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
frame.convert();
}
//Main method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new Application();
}
}
You have to slightly modify your frame to add controls to the content pane. You can do some work after frame is created, then call alert.
import java.awt.*;
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;
public class PleaseWait extends JFrame {
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel();
private static JButton OK = new JButton("OK");
BorderLayout borderLayout1 = new BorderLayout();
JPanel contentPane;
int count;
public PleaseWait(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(width, height));
this.setTitle("Chill For A Sec");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
OK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
contentPane.add(mainLayout);
}
public void convert(){
count = 0;
for (int i = 0; i <10; i++){
System.out.println("Copy "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
count++;
}
alert();
}
public void alert(){
OK.setEnabled(true);
// String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + count + " files Converted");
}
}

Categories

Resources