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.
Related
I am currently working on my school project to practice vocabulary, I have a method in my GUI that creates new vocabulary and the name of the list, I wanted to create a button that adds more Panels with input fields just this prototype image.
My idea is that when the user clicks
AddMoreButton it will add one JPanel just like P Panel, then the user can write vocabulary to send it to my database, is it possible to create something that?, I tried looping the P panel but it did not not change, any help would be appreciated.
private JPanel SetUpCreate() {
JPanel createPanel = new JPanel();
nameListInput = new JTextField(INPUT_FIELD_WIDTH);
termInput = new JTextField(INPUT_FIELD_WIDTH);
defintionInput = new JTextField(INPUT_FIELD_WIDTH);
p = new JPanel();
doneCreate = new JButton("Done");
doneCreate.addActionListener(new DoneCreateButtonAction());
addMoreButton = new JButton("Add");
addMoreButton.addActionListener(new AddMorePanelsListener());
p.setBorder(new BevelBorder(BevelBorder.RAISED));
p.add(termInput);
p.add(defintionInput);
JScrollPane pane = new JScrollPane(p);
createPanel.add(nameListInput);
createPanel.add(p);
createPanel.add(pane);
createPanel.add(doneCreate);
return createPanel;
}
private class DoneCreateButtonAction implements ActionListener {
public DoneCreateButtonAction() {
super();
}
public void actionPerformed(ActionEvent e) {
String namelist = nameListInput.getText();
String termglosa = termInput.getText();
String defintionglosa = defintionInput.getText();
try {
if (model.createWordList(namelist) && (model.createGlosa(termglosa, defintionglosa))) {
cl.show(cardPanel, "home");
}
} catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "skapelsen av listan fungerar ej.");
}
}
}
private class AddMoreButtonAction implements ActionListener {
public AddMoreButtonAction() {
super();
}
public void actionPerformed(ActionEvent e) {
}
}
What I understand from your question is that you want to add another panel every time the user clicks the Add button and the panel to add contains fields for entering a word and its definition.
I see JScrollPane appears in the code you posted in your question. I think this is the correct implementation. In the below code, every time the user clicks the Add button I create a panel that contains the fields for a single word definition. This newly created panel is added to an existing panel that uses GridLayout with one column. Hence every time a new word definition panel is added, it is placed directly below the last word panel that was added and this GridLayout panel is placed inside a JScrollPane. Hence every time a word definition panel is added, the GridLayout panel height increases and the JScrollPane adjusts accordingly.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class MorPanel implements ActionListener, Runnable {
private static final String ADD = "Add";
private JFrame frame;
private JPanel vocabularyPanel;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
String actionCommand = actionEvent.getActionCommand();
switch (actionCommand) {
case ADD:
vocabularyPanel.add(createWordPanel());
vocabularyPanel.revalidate();
vocabularyPanel.repaint();
break;
default:
JOptionPane.showMessageDialog(frame,
actionCommand,
"Unhandled",
JOptionPane.ERROR_MESSAGE);
}
}
public JButton createButton(String text) {
JButton button = new JButton(text);
button.addActionListener(this);
return button;
}
public JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(ADD));
return buttonsPanel;
}
private JScrollPane createMainPanel() {
vocabularyPanel = new JPanel(new GridLayout(0, 1));
vocabularyPanel.add(createWordPanel());
JScrollPane scrollPane = new JScrollPane(vocabularyPanel);
return scrollPane;
}
private JPanel createWordPanel() {
JPanel wordPanel = new JPanel();
JLabel wordLabel = new JLabel("Enter Term");
JTextField wordTextField = new JTextField(10);
JLabel definitionLabel = new JLabel("Enter Term Definition");
JTextField definitionTextField = new JTextField(10);
wordPanel.add(wordLabel);
wordPanel.add(wordTextField);
wordPanel.add(definitionLabel);
wordPanel.add(definitionTextField);
return wordPanel;
}
private void showGui() {
frame = new JFrame("Vocabulary");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.setSize(480, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new MorPanel());
}
}
As your code is not an Minimal Reproducible Example, I cannot provide further assistance than this:
Red part: Your main JPanel with BoxLayout
Green part: another JPanel with your JTextField in it.
Purple part: JScrollPane
Blue parts: custom JPanels with 2 panes in them, one on top for the number, one on the bottom for both JTextFields and icon, so I would say GridBagLayout or BoxLayout + FlowLayout
Orange part: JPanel with GridBagLayout or FlowLayout
Each time you clic on the + icon, you just create a new instance of the custom blue JPanel and that's it.
Im using blue j for a project which is a java framework (not through my choice)
I cant get it to print out what seat they have chosen because it always selects the 1st value A1.
Its a seating plan that displays and image and a combo box in which you can select your seat for exmaple A1 and upon the button click save it prints out the seat you have chosen in a dialog box.
Help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SeatingChart extends JFrame
{
private JLabel infoLabel;
// Get the list of field names, used for ordering.
String[] ordering =
{"A1","A2","A3","A4",
"B1","B2","B3","B4",
"C1","C2","C3","C4","D1","D2","D3","D4"};
String chosenSeat;
String ticket= "1" ;
int ticketValue = Integer.parseInt(ticket);
/**
* Main method for starting the system from a command line.
*/
public static void main(String[] args)
{
SeatingChart gui = new SeatingChart();
}
/**
* Create a visual aspect and display its GUI on screen.
*/
public SeatingChart()
{
super("Choose Your seats");
makeFrame();
}
/**
* Quit function: quit the application.
*/
private void quit()
{
System.exit(0);
}
private void play()
{
JFrame frames = new JFrame("Sample frame");
frames.setSize(400, 400);
frames.setVisible(false);
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(frames, "You have chosen the seat " +chosenSeat);
}
/**
* Create the complete application GUI.
*/
public void makeFrame ()
{
// the following makes sure that our application exits when
// the user closes its window
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) getContentPane();
contentPane.setBorder(new EmptyBorder(6, 10, 10, 10));
makeMenuBar(); //calls the menu bar method
// Create the center with image
JPanel centerPane = new JPanel();
{
centerPane.setLayout(new BorderLayout(8, 8));
JLabel image = new JLabel(new ImageIcon("SeatingChart.jpg"));
image.setSize (20,20);//dont work
centerPane.add(image, BorderLayout.NORTH);
centerPane.setBackground(Color.WHITE);
infoLabel = new JLabel("Please use the chart to select where you would like to sit and save it. Do this for how many tickets you have");
infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
centerPane.add(infoLabel, BorderLayout.CENTER);
}
contentPane.add(centerPane, BorderLayout.EAST);
JPanel leftPane = new JPanel();
{
leftPane.setLayout(new BorderLayout(8, 8));
// Set up components for ordering the list
JPanel orderingPanel = new JPanel();
orderingPanel.setLayout(new BorderLayout());
orderingPanel.add(new JLabel("Choose your seat:"), BorderLayout.NORTH);
// Create the combo box.
JComboBox formatList = new JComboBox(ordering);
orderingPanel.add(formatList, BorderLayout.CENTER);
leftPane.add(orderingPanel, BorderLayout.NORTH);
formatList.setSelectedIndex(0);
chosenSeat = formatList.getSelectedItem().toString();
//formatList.removeItemAt(formatList.getSelectedIndex());
}
contentPane.add(leftPane, BorderLayout.CENTER);
JPanel toolbar = new JPanel();
{
toolbar.setLayout(new GridLayout(1, 0));
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play();
}
});
toolbar.add(button);
button = new JButton("Next");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// This button would allow the use to go to the next step
}
});
toolbar.add(button);
}
contentPane.add(toolbar, BorderLayout.SOUTH);
// building is done - arrange the components
pack();
// place this frame at the center of the screen and show
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(d.width/2 - getWidth()/2, d.height/2 - getHeight()/2);
setVisible(true);
}
/**
* Create the main frame's menu bar.
*/
private void makeMenuBar()
{
final int SHORTCUT_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu menu;
JMenuItem item;
// create the File menu
menu = new JMenu("File");
menubar.add(menu);
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quit();
}
});
menu.add(item);
}
}
You set the chosenSeat field immediately after creating the formatList combo box. At that moment, the user has not even had a chance to pick a seat and seat A1 is selected by default. If you set chosenSeat in the play method, it should reflect the seat picked by your user.
I think the new JFrame in the play method - as already mentioned by mKorbel - is not needed, since you can use the application frame (this) as the parent component for the call to the JOptionPane.showMessageDialog method:
private void play() {
// todo: frames is not needed.
//JFrame frames = new JFrame("Sample frame");
//frames.setSize(400, 400);
//frames.setVisible(false);
//frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chosenSeat = formatList.getSelectedItem().toString();
// todo: use the application frame as the parent.
//JOptionPane.showMessageDialog(frames, "You have chosen the seat " + chosenSeat);
JOptionPane.showMessageDialog(this, "You have chosen the seat " + chosenSeat);
}
I changed the code again. But now when I run the code, The text box is very small. Only whn I choose either of the left, center or the right alignment, will the text box size change.
Where did I make the mistake.
I have written the below program. When I click on the left, right or the center button, the program should also read the value in the column size textbox and then automatically resize the message textfield. BUt I cannot seem to do it. Any insight will be greatly appreciated.
package workingwithjtextfields;
package workingwithjtextfields;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.*;
public class WorkingwithJTextFields extends JFrame
{
// private int size = 100;
private JTextField jtfMessage = new JTextField(100);
private JTextField jtfColumn = new JTextField(5);
private JRadioButton jrbLeft,jrbCenter,jrbRight;
public static void main(String[] args) //Main program begins here.
{
JFrame frame = new WorkingwithJTextFields();//Instantiating an object.
frame.setTitle("Exercise 17.11");//Setting the frame title.
frame.setSize(470,110);//Setting the size.
frame.setLocationRelativeTo(null);//Setting the location.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// Default closing options.
frame.setVisible(true);//Setting visibility to true.
}//End of main program
public WorkingwithJTextFields()
{
// jtfMessage.setColumns(100);
final JPanel parent = new JPanel();
parent.setLayout(new GridLayout(2,1,3,3));
final JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT,30,0));
p1.add(new JLabel("TextField",SwingConstants.CENTER));
jtfMessage= new JTextField("Type anything",SwingConstants.RIGHT);
jtfMessage.setHorizontalAlignment(SwingConstants.CENTER);
p1.add(jtfMessage);
parent.add(p1);
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(1,3));
jpRadioButtons.add(jrbLeft= new JRadioButton("Left"));
jpRadioButtons.add(jrbCenter = new JRadioButton("Center"));
jpRadioButtons.add(jrbRight = new JRadioButton("Right"));
jpRadioButtons.setBorder(new TitledBorder("Horizontal Border"));
final JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,2,1,1));
p2.add(jpRadioButtons);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(1,1,1,1));
p3.add(new JLabel("Column Size"));
jtfColumn= new JTextField("60",SwingConstants.RIGHT);
jtfColumn.setHorizontalAlignment(SwingConstants.CENTER);
p3.add(jtfColumn);
Border lineBorder = new LineBorder(Color.LIGHT_GRAY,1);
p3.setBorder(lineBorder);
p2.add(p3);
parent.add(p2);
add(parent);
jrbLeft.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtfMessage.setHorizontalAlignment(SwingConstants.LEFT);
jrbCenter.setSelected(false);
jrbRight.setSelected(false);
jtfMessage.setColumns(Integer.parseInt(jtfColumn.getText()));
// p1.revalidate();
// p1.repaint();
}
}
);
jrbCenter.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtfMessage.setHorizontalAlignment(SwingConstants.CENTER);
jrbLeft.setSelected(false);
jrbRight.setSelected(false);
jtfMessage.setColumns(Integer.parseInt(jtfColumn.getText()));
}
}
);
jrbRight.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jtfMessage.setHorizontalAlignment(SwingConstants.RIGHT);
jrbCenter.setSelected(false);
jrbLeft.setSelected(false);
jtfMessage.setColumns(Integer.parseInt(jtfColumn.getText()));
}
}
);
}
}
The main problem is with GridLayout.
GridLayout, by design, gives equal width and height to the components in the column/width based on the available space of the parent container.
Instead, try using something like FlowLayout or GridBagLayout which work with the components preferred size instead
In our aplication we use Metal L&F. We are using a floatable JToolBar; it happens that when doing the drag behavior it appears with the Windows L&F.
May anyone say me how to keep Metal L&F when dragging the JToolBar?
Thanks
P.D. Our JToolBar is within a JPanel container that user BorderLayout Layout Manager.
Maybe I explained badly my question. So I post an example taken from The Java Tutorials to give anyone an idea of what happens to my application.
If you execute the following code the main JFrame appears decorated with Ocean Theme; but when I drag the JToolBar its decorated is not Ocean. What can I do??.
Many thanks in advance
package components;
/*
* ToolBarDemo.java requires the following addditional files:
* images/Back24.gif
* images/Forward24.gif
* images/Up24.gif
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = "images/"
+ imageName
+ ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ToolBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setsLF();
createAndShowGUI();
}
});
}
/**
*
*/
private static void setsLF() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log (java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
return;
}
}
Looks like nowadays the toplevel container of the ripped of toolBar is of type JDialog, so you have the set the lafDecoration for that as well:
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
JDialog.setDefaultLookAndFeelDecorated(true);
Works for jdk7 and vista, didn't test other environments.
I made a small project as you described:
public class LafTest
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(500, 500);
JPanel panel = new JPanel(new BorderLayout());
JToolBar toolbar = new JToolBar();
toolbar.add(new JButton("button1"));
toolbar.add(new JButton("button2"));
panel.add(toolbar, BorderLayout.PAGE_START);
frame.add(panel);
frame.setVisible(true);
}
}
Works fine for me, all the time the JToolBar has Metal-LAF.
(OS: Windows 7 x64, java version "1.7.0_09")
Please compare your code with this snippet. Propably you used the UIManager-class somewhere. If you still cannot fix this issue, you should post some of the used code and maybe some more details about your OS and the used Java version.
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");
}
}