Add Video Frame to JTabbed pane - java

I have created a java tabbed pane. In the tabbed pane i have created a tab called Video. I want whenever i click on the video tab a video should automatically be played on the tab panel itself. Can I do this? If yes please tell me how to do it.

You have to add a ChangeListener to your JTabbedPane component and override the stateChanged method:
tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane.getSelectedIndex() == 2) {
// start playing the media clip in tab 2
mediaPlayer.start();
}
}
}
});
Here is a complete, working code:
package tabvideo;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.media.CannotRealizeException;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.Manager;
public class TabbedPaneVideoDemo extends JPanel {
Player mediaPlayer = null;
public TabbedPaneVideoDemo() {
super(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
ImageIcon icon = createImageIcon("images/icon.gif");
JComponent panel1 = makeTextPanel("Panel #1");
tabbedPane.addTab("Tab 1", icon, panel1, "Does nothing");
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
JComponent panel2 = makeTextPanel("Panel #2");
tabbedPane.addTab("Tab 2", icon, panel2, "Does twice as much nothing");
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
JComponent panel3 = makeTextPanel("Panel #3");
tabbedPane.addTab("Tab 3", icon, panel3, "Still does nothing");
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
JComponent panel4 = makeVideoPanel("somevideo.avi");
tabbedPane.addTab("Tab 4", icon, panel4, "Playes video!");
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane.getSelectedIndex() == 2) {
// start playing the media clip in tab 2
mediaPlayer.start();
}
}
}
});
// Add the tabbed pane to this panel.
add(tabbedPane);
// The following line enables to use scrolling tabs.
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
protected JPanel makeVideoPanel(String filename) {
JPanel panel = new JPanel(false);
panel.setLayout(new BorderLayout()); // use a BorderLayout
// Use lightweight components for Swing compatibility
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
try {
URL mediaURL = new File(filename).toURI().toURL();
// create a player to play the media specified in the URL
mediaPlayer = Manager.createRealizedPlayer(mediaURL);
// get the components for the video and the playback controls
Component video = mediaPlayer.getVisualComponent();
Component controls = mediaPlayer.getControlPanelComponent();
if (video != null)
panel.add(video, BorderLayout.CENTER); // add video component
if (controls != null)
panel.add(controls, BorderLayout.SOUTH); // add controls
} // end try
catch (NoPlayerException noPlayerException) {
System.err.println("No media player found");
} // end catch
catch (CannotRealizeException cannotRealizeException) {
System.err.println("Could not realize media player");
} // end catch
catch (IOException iOException) {
System.err.println("Error reading from the source");
} // end catch
return panel;
} // end MediaPanel constructor
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = TabbedPaneVideoDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
/**
* 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("TabbedPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add content to the window.
frame.add(new TabbedPaneVideoDemo(), BorderLayout.CENTER);
// 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() {
// Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}

use the JTabbedPane getModel() of type SingleSelectionModel, add a ChangeListener to the model, you'll get an event, when a tab has been selected.

EDIT: Do you mean, it should run automatically w/o any button press, then use the JTabbedPane getModel() of type SingleSelectionModel, add a ChangeListener to the model, you'll get an event, when a tab has been selected.
If you mean it should run inside the small tab, maybe you can run a Thread that displays frames of IconImages.

Related

Java Card Layouts using Choice

I want to create a program with a GUI where I have a Choice with three different options.
I have to realize it with CardLayout but my problem is that I don't know how to switch the CardLayoutPanel to the one I selected in the Choice.
Choice ch = new Choice();
Panel cl = new Panel(new CardLayout());
Panel one = new Panel();
Panel two = new Panel();
Panel three = new Panel();
and in the constructor I have:
// CARD LAYOUT PANELS
cl.add(one, "1");
cl.add(two, "2");
cl.add(three, "3");
f.setLayout(new FlowLayout());
// CHOICE-OPTIONS
ch.add("one");
ch.add("two");
ch.add("three");
How can I add an ActionListener to switch between the different Panels using the Choice ?
(Please don't comment google it - I already did, otherwise I wouldn't ask)
Thank you!
Here is a SSCCE (Short Self Contained Correct Example). Notes after the code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class AwtTest0 extends WindowAdapter implements ItemListener {
private Frame frame;
private Panel cards;
public void itemStateChanged(ItemEvent event) {
CardLayout layout = (CardLayout) cards.getLayout();
if (event.getStateChange() == ItemEvent.SELECTED) {
Object obj = event.getItem();
String name = obj.toString();
layout.show(cards, name);
}
}
public void windowClosing(WindowEvent event) {
System.exit(0);
}
private Panel createCard(String text) {
Panel card = new Panel();
Label label = new Label(text);
card.add(label);
return card;
}
private Panel createCards() {
cards = new Panel(new CardLayout());
cards.add(createCard("1"), "one");
cards.add(createCard("2"), "two");
cards.add(createCard("3"), "three");
return cards;
}
private Panel createChoice() {
Panel panel = new Panel();
Choice ch = new Choice();
ch.add("one");
ch.add("two");
ch.add("three");
ch.addItemListener(this);
panel.add(ch);
return panel;
}
private void showGui() {
frame = new Frame();
frame.addWindowListener(this);
frame.add(createChoice(), BorderLayout.PAGE_START);
frame.add(createCards(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
final AwtTest0 instance = new AwtTest0();
EventQueue.invokeLater(() -> instance.showGui());
}
}
In method main I call method invokeLater which explicitly launches the EDT (Event Dispatch Thread). The GUI must run on this thread.
In order to cause the application to terminate when you click the close window button (which is usually an X in the top corner of the window), you add a WindowListener.
When you add components to the Frame, you are actually adding them to the content pane which is a Panel that has BorderLayout layout manager.
Choice does not support ActionListener, it supports ItemListener. Hence the above code implements ItemListener.

How to create multiple JPanels with JTextField input?

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.

How to Change setVisible() on Panels in different Java Class

package com.spiralfive.inventory;
import java.awt.Font;
import java.awt.Panel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.BorderLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
public class MainFile extends JApplet implements MouseListener {
// Declare the initial components
private JButton btnNewInventory;
private JButton btnMarkDown;
private JButton btnProcessSales;
private JButton btnActive;
private JButton btnStats;
private Panel mainPanel;
private Panel menuPanel;
private Panel inventoryPanel;
private Panel setactivePanel;
// Call the Initializer...
public void init() {
initComponents();
}
// Initialize the Main Components - Mostly Menu Items
private void initComponents() {
// Main Form Components
mainPanel = new Panel();
menuPanel = new Panel();
inventoryPanel = new Panel();
setactivePanel = new Panel();
btnNewInventory = new JButton("New Inventory");
btnActive = new JButton("Set Active");
btnMarkDown = new JButton("Mark Down");
btnProcessSales = new JButton("Process Sale");
btnStats = new JButton("Statistics");
// Enable Mouse Interactivity
btnNewInventory.addMouseListener(this);
btnMarkDown.addMouseListener(this);
btnProcessSales.addMouseListener(this);
btnActive.addMouseListener(this);
btnStats.addMouseListener(this);
// Set the Fonts
Font buttonFont = new Font("Arial", Font.PLAIN, 20);
// Apply Fonts To Menu
btnNewInventory.setFont(buttonFont);
btnMarkDown.setFont(buttonFont);
btnProcessSales.setFont(buttonFont);
btnActive.setFont(buttonFont);
btnStats.setFont(buttonFont);
// Set Panel Layout For Menu Items
menuPanel.setLayout(new java.awt.GridLayout(1,6));
// Add the Components
menuPanel.add(btnNewInventory);
menuPanel.add(btnActive);
menuPanel.add(btnMarkDown);
menuPanel.add(btnProcessSales);
menuPanel.add(btnStats);
// Add The Menu To the Main Panel
mainPanel.add(BorderLayout.NORTH, menuPanel);
// Make Inventory Load by Default
createPanels();
makeInvVisible();
// Set It All Visible
add(mainPanel);
}
// Create the Panels Used in this applet
public void createPanels() {
NewInventory inventoryPanel = new NewInventory();
inventoryPanel.setLayout(new java.awt.GridLayout(6,2));
mainPanel.add(BorderLayout.CENTER, inventoryPanel);
SetActive setactivePanel = new SetActive();
setactivePanel.setLayout(new java.awt.GridLayout(6,2));
mainPanel.add(BorderLayout.CENTER, setactivePanel);
}
public void makeInvVisible() {
inventoryPanel.setVisible(true);
mainPanel.repaint();
}
public void makeInvDisappear() {
inventoryPanel.setVisible(false);
mainPanel.repaint();
}
public void makeActiveVisible() {
setactivePanel.setVisible(true);
mainPanel.repaint();
}
public void makeActiveDisppear() {
setactivePanel.setVisible(false);
mainPanel.repaint();
}
public void mouseClicked(MouseEvent e) {
// Determine Which Button Has Been Clicked
JButton currentButton = (JButton)e.getComponent();
// New Inventory Button
if(currentButton == btnNewInventory) {
makeInvVisible();
makeActiveDisppear();
}
// Set Active Button
else if(currentButton == btnActive) {
makeActiveVisible();
makeInvDisappear();
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
I am using the code above attempting to make a new Panel() appear and the existing panel disappear when a button is clicked by using setVisible. However, I cannot get the Panel() to change. Nothing happens when the buttons are clicked, which are set to change setVisible to false on the current Panel and true on the requested Panel.
I am fairly certain it is because the panels are set a private in a different class (initComponents). How do I access the setVisible property on the panels? Or, is this even what's wrong?
Add
this.validate();
in the makeActiveVisible() method.
Swing components have a default state of being invalid and won't be painted to the screen unless validated (by calling the .validate() method on either the component itself or on one of the parent containers).
See also
repaint() in Java

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.

How to keep Metal L&F when dragging JToolBar

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.

Categories

Resources