I wanted to add a scrollbar to my photo viewer but the it gives me the error that a non static variable cannot be referenced from a static context.
To be exact, I'm trying to add a scrollbar to a JPanel. Also, if I make JScrollPane scrollBar a static variable, then the photo wont appear. TIA
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.JScrollPane;
public class PhotoViewer
{
// Instance fields.
private FilenameFilter fileNameFilter;
private JFileChooser fileChooser;
private JMenuBar menuBar;
private JPanel mainPanel;
private static JScrollPane scrollBar;
public PhotoViewer() // Constructor.
{
// Main JPanel with a grid style layout.
mainPanel = new JPanel(new GridLayout());
// Jlabel to display photo on.
final JLabel imageView = new JLabel();
// Adds the JLabel ontop of the JPanel.
mainPanel.add(imageView);
// Adds a scroll bar.
scrollBar = new JScrollPane(mainPanel);
scrollBar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// Creates a file chooser to find a photo.
fileChooser = new JFileChooser();
// Creates a new menubar at the top of the JPanel.
menuBar = new JMenuBar();
// Adds a menu within the JMenuBar.
JMenu menu = new JMenu("View new photo");
// Adds the additional menu ontop of the original JMenuBar.
menuBar.add(menu);
// Option to browse for a new photo.
JMenuItem browse = new JMenuItem("Browse");
// Adds the browse option ontop of the 'View new photo' button.
menu.add(browse);
// Creates an actionlistener to follow what the user is doing.
browse.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int result = fileChooser.showOpenDialog(mainPanel);
// Displays the image if approved by JFileChooser.
if (result==JFileChooser.APPROVE_OPTION)
{
// Obtains the selected file by the user.
File singleImage = fileChooser.getSelectedFile();
try
{
// Displays the image if no exception.
Image displayImage = ImageIO.read(singleImage);
imageView.setIcon(new ImageIcon(displayImage));
} catch(Exception e)
{
// Displays the exception caught by the program in a JOptionPane window.
e.printStackTrace();
JOptionPane.showMessageDialog(mainPanel, e, "Load failure!", JOptionPane.ERROR_MESSAGE);
}
}
}
});
} // end of constructor PhotoViewer
public void loadImages(File directory) throws IOException
{
// Throws an exception to be caught.
File[] imageFiles = directory.listFiles(fileNameFilter);
BufferedImage[] images = new BufferedImage[imageFiles.length];
} // end of method loadImages(File directory)
public Container getPanel()
{
// Hands execution back to the mainPanel function.
return mainPanel;
}// end of method getPanel()
public JMenuBar getMenuBar()
{
// Hands execution back to the menuBar function.
return menuBar;
}// end of method getMenuBar()
public JScrollPane getScrollBar()
{
// Hands execution back to the menuBar function.
return scrollBar;
}// end of method getScrollBar()
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
// Input all the compoenents of the photo viewer to the JFrame to display them.
PhotoViewer imageList = new PhotoViewer();
// Creates a new JFrame to display everything.
JFrame mainFrame = new JFrame("Photo Viewer");
// 'Throws away' the JFrame on close.
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Adds all the different components to the JFrame.
mainFrame.add(imageList.getPanel());
mainFrame.add(imageList.getScrollBar());
mainFrame.setJMenuBar(imageList.getMenuBar());
mainFrame.setLocationByPlatform(true);
// Packs all the components into the JFrame.
mainFrame.pack();
// Sets the size of the JFrame.
mainFrame.setSize(1500,1500);
// Allows us to see the JFrame.
mainFrame.setVisible(true);
}
});
} // end of method main(String[] args)
} // end of class PhotoViewer
There is no need to add mainPanel and scrollBar separately, as scrollBar already contains mainPanel. Just execute mainFrame.add(imageList.getScrollBar()); and don't call mainFrame.add(imageList.getPanel()); at all. A single control can be added only to one container.
Default layout of JFrame is BorderLayout. When you add controls to BorderLayout without specifying layout constraint it places the control in BorderLayout.CENTER, effectively replacing whatever there was before.
Just a minor change to your code :)
instead of
scrollBar = new JScrollPane(mainPanel);
use
scrollBar = new JScrollPane(imageView);
mainPanel.add(scrollBar);
and there is no need for
mainFrame.add(imageList.getScrollBar());
Related
I'm trying to use a few JDialogs inside my form JPanel to notify the user of incorrect data and form submission.
I'm just a bit confused with the JDialog constructor. I'd want to link the dialog to the panel (only because that's where it's created), but obviously the only owner parameters that are allowed are top level Frames (which I don't think I can access from the JPanel), or a Dialog (which I can't see helping me).
I could pass a reference for the Frame down to the JPanel, but isn't that a bit strange design wise? Or am I misunderstanding the class, or just more generally where the JDialog should be instantiated?
Hope I've made myself clear, I can make a sscce if it helps. Thanks.
the only owner parameters that are allowed are top level Frames (which I don't think I can access from the JPanel
You can access the parent frame of the panel by using:
Window window = SwingUtilities.windowForComponent( yourPanelHere );
Then just use the window as the owner of the dialog.
JComponent.getTopLevelAncestor gives you the owner of the JPanel:
Returns the top-level ancestor of this component (either the
containing Window or Applet), or null if this component has not been
added to any container.
You can try it:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class DialogTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
public void run() {
DialogFrame frame = new DialogFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* Frame contains menu. When we choose menu "File-> About" JDialog will be shown
*/
class DialogFrame extends JFrame {
public DialogFrame() {
setTitle("DialogTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// Add About & Exit.
// Choose About - > About
JMenuItem aboutItem = new JMenuItem("About");
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (dialog == null) //if not
{
dialog = new AboutDialog(DialogFrame.this);
}
dialog.setVisible(true); // to show dialog
}
});
fileMenu.add(aboutItem);
// When Exit
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
fileMenu.add(exitItem);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private AboutDialog dialog;
}
/*
* Modal dialog waits on click
*/
class AboutDialog extends JDialog {
public AboutDialog(JFrame owner) {
super(owner, "About DialogTest", true);
// Mark with HTML centration
add(new JLabel(
"<html><h1><i>Все о Java</i></h1><hr>"
+ "Something about java and JDialog</html>"),
BorderLayout.CENTER);
// When push "ok" dialog window will be closed
JButton ok = new JButton("ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
// Button ОК down of panel
JPanel panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH);
setSize(260, 160);
}
}
I'm trying to make a main menu for the board game risk. There's a custom background image, and ideally I would like the buttons to appear over the image. However when I run my code, only the button called "New Game" appears, and the other buttons will appear if you hover the mouse over them. I have tried just about everything (there are similar problems on here) but can't seem to fix the problem. Maybe it has something to do with my code? I appreciate any help/suggestions!
package View;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SpringLayout;
/**
* These classes set up the GUI of the Risk program.
* The main menu, dialog for setting player count, dialog for name/color settings for each
* player, the Risk game board, and a menu used during a Risk game session are included.
**/
public class Menu extends JFrame {
private JPanel mainPanel;
private JButton newGameButton;
private JButton loadGameButton;
private JButton quitButton;
private JButton ruleButton;
private String newGameButtonName = "newGameBtn";
private String loadGameButtonName = "loadGameBtn";
private String quitButtonName = "quitBtn";
private String ruleButtonName = "rulebtn";
//private SpringLayout mainLayout;
private static BufferedImage img;
/**
* Constructs the main menu.
**/
public Menu()
{
add( mainMenu( ) );
//setTitle("Risk: UConn Edition");
setPreferredSize(new Dimension(640, 700));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
toFront();
pack();
setVisible(true);
}
/**
* creates the buttons for the jPanel
*
* #return
*/
private JPanel mainMenu()
{
// Creates the panel
mainPanel = new JPanel();
// Sets Layout
//mainLayout = new SpringLayout();
mainPanel.setLayout(null);
// Creates buttons
newGameButton = new JButton("New Game");
newGameButton.setBounds(20,300,150,50);
newGameButton.setOpaque(false);
newGameButton.setContentAreaFilled(false);
newGameButton.setForeground(Color.RED);
newGameButton.setBackground(Color.BLUE);
loadGameButton = new JButton("Load Game");
loadGameButton.setBounds(20,400,150,50);
//loadGameButton.setOpaque(false);
//loadGameButton.setContentAreaFilled(false);
loadGameButton.setForeground(Color.RED);
quitButton = new JButton("Quit");
quitButton.setBounds(490,400,150,50);
quitButton.setOpaque(false);
quitButton.setContentAreaFilled(false);
quitButton.setForeground(Color.RED);
ruleButton = new JButton("Rules");
ruleButton.setBounds(490,300,150,50);
ruleButton.setOpaque(false);
ruleButton.setContentAreaFilled(false);
ruleButton.setForeground(Color.RED);
// Sets button commands
newGameButton.setActionCommand(newGameButtonName);
loadGameButton.setActionCommand(loadGameButtonName);
quitButton.setActionCommand(quitButtonName);
// Adds buttons to mainPanel
mainPanel.add(newGameButton);
mainPanel.add(loadGameButton);
mainPanel.add(quitButton);
mainPanel.add(ruleButton);
// add(mainPanel);
return mainPanel;
}
private Image createImage(){
try {
img = ImageIO.read(
Menu.class.getResource("../resource/riskUconn.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
/**
* paint method
*/
#Override
public void paint (Graphics g) {
Image img = createImage();
g.drawImage(img, 20,20,this);
super.paint(g);
}
// Action listeners for Menu
protected void riskViewActionListeners(ActionListener evt)
{
newGameButton.addActionListener(evt);
loadGameButton.addActionListener(evt);
quitButton.addActionListener(evt);
}
public static void main(String [] args){
Menu m = new Menu();
}
}
Painting components doesn't always notify the parent or child components. Instead of overriding paint, try overriding paintComponent and paint your background there, this is what paintComponent is really meant for, painting the background.
You should avoid overriding paint of top level containers.
Most top level containers have a series of layers, including the JRootPane, contentPane and even a glassPane, all of which will paint over the top of the a frame.
Instead, create a custom component, which extends from something like JPanel and use it as you base component. You can override it's paintComponent and paint the background within it. Then add this component to your frame, maybe even making it the content pane.
Remember, if a component is opaque, it will cover any child components
You should also avoid loading resources from within any paint method (especially continuously reloading them) as this can have a serve affect on the performance of your program. Painting should paint as fast as it can.
For example and example
Can anyone help me? Whenever I ran the codes below, it always returns a blank frame, I don't know where I did wrong. Can you guys help me debug this? I already added the components to the panel, and the panel to the frame, but still it returns a blank output.
Here is the output I'm getting:
While this is what is required.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JRadioButton;
/**
*
* #author Chareux
*/
//Declaring Variables
public class TestUI {
private JFrame frm_main;
private JPanel sr_pnl;
private JLabel sr_lbl;
private JLabel sr_lbl2;
private JLabel ret_optn_lbl;
private JLabel ret_rsn_lbl;
private ButtonGroup ret_ops;
private JTextField sr_txtnum;
private JTextField sr_ret_txtrsn;
private JButton sr_start;
private JRadioButton ret_optn_rdbn_y;
private JRadioButton ret_optn_rdbn_n;
public TestUI(){
start();
}
public void start(){
//Creating the JFrame
frm_main = new JFrame("Service Desk SR Tool");
frm_main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm_main.setSize(500,450);
frm_main.setLocationRelativeTo(null);
frm_main.setResizable(false);
frm_main.setVisible(true);
// the Panel
sr_pnl = new JPanel();
//Components
sr_lbl = new JLabel("SERVICE DESK SR TIMER!");
sr_lbl2 = new JLabel("SR number: ");
sr_txtnum = new JTextField("Enter SR number here..",20);
ret_optn_lbl = new JLabel("Returning Ticket?");
ret_optn_rdbn_y = new JRadioButton("Yes");
ret_optn_rdbn_n = new JRadioButton("No");
ret_rsn_lbl = new JLabel("Reason: ");
sr_ret_txtrsn = new JTextField("Enter Reason number here..",20);
sr_start = new JButton("START!");
//adding the Components to the panel
sr_pnl.add(sr_lbl);
sr_pnl.add(sr_lbl2);
sr_pnl.add(sr_txtnum);
sr_pnl.add(ret_optn_lbl);
sr_pnl.add(ret_optn_rdbn_y);
sr_pnl.add(ret_optn_rdbn_n);
sr_pnl.add(ret_rsn_lbl);
sr_pnl.add(sr_ret_txtrsn);
sr_pnl.add(sr_start);
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
}
public static void main(String[] args) {
new TestUI();
}
}
I'd recommend to use a nested or compound layout for this task. See further tips in comments in the source.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SRTool {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new GridLayout(0,1,6,6));
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
// show the BG
gui.setBackground(Color.CYAN);
// center the label text
gui.add(new JLabel(
"Service Desk SR Tool", SwingConstants.CENTER));
// create a lyout that can center multiple components
FlowLayout layout = new FlowLayout(FlowLayout.CENTER,5,5);
JPanel srPanel = new JPanel(layout);
gui.add(srPanel);
srPanel.add(new JLabel("SR:"));
srPanel.add(new JTextField(8));
JPanel returnTicketPanel = new JPanel(layout);
gui.add(returnTicketPanel);
returnTicketPanel.add(new JLabel("Returning Ticket?"));
returnTicketPanel.add(new JCheckBox());
JPanel reasonPanel = new JPanel(layout);
gui.add(reasonPanel);
reasonPanel.add(new JLabel("Reason:"));
reasonPanel.add(new JTextField(14));
JPanel buttonPanel = new JPanel(layout);
gui.add(buttonPanel);
buttonPanel.add(new JButton("Start!"));
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See https://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Add frm_main.validate() in the end of start()
public void start(){
/*
...
Same As Above
...
*/
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
frm_main.validate(); // Add this line ******
}
I have a JFrame with it's content pane. JMenuBar is docked on the north of the pane and JLabel (status bar of sorts) on the south.
In the middle is a JTabbedPane. Each tab is a "document". It contains a JScrollBar and a JPanel in it's viewport.
It goes on and on (JPanel of the viewport has more JPanels, that can have more of them, etc...), but for this example, lets just say that that JPanel (in the viewport) can, or cannot fit into the window space (so it cannot, or can force scrollBars to be represented on the screen).
When it fits the window, everyting is fine, but as soon as I set it's height to be too hight to fit inside a window, JMenuBar gets squished on the top.
I'd like to prevent that (without having to specify the absolute height for the JMenuBar, it'd probably work, but it's kind of cheap), since it shouldn't happen in the first place.
Here's SCCE (It's not really short, but you only need to look at the lines 37 to 117, and I have marked all the lines that have something to do with layout with //TODO). Also, to see when problem occurs or when it doesn't occur, change height value in the line 88 inbetween 2000 and 200. You also need a MiG Layout library, of course.
Here's the code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import net.miginfocom.swing.MigLayout;
class Menu extends JMenuBar
{
private static final long serialVersionUID = 1L;
public Menu()
{
JMenu fileMenu = new JMenu("file");
this.add(fileMenu);
}
}
class DisplayGUI
{
JTabbedPane documentSelector;
void addNewDocument(String name)
{
Document newDocument = new Document();
newDocument.addChapter(new Chapter(), 1);
documentSelector.add(newDocument, name);
}
public DisplayGUI()
{
JFrame masterWindow = new JFrame("name");
masterWindow.setSize(1100, 800);
masterWindow.setMinimumSize(new Dimension(400, 400));
masterWindow.setLocationRelativeTo(null);
masterWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel rootPanel = new JPanel();
rootPanel.setLayout(new MigLayout()); //TODO Here is layout set for the content pane of the main JFrame
Menu menuBar = new Menu();
rootPanel.add(menuBar, "span, north"); //TODO Here is menu bar added to the JFrame, it's docked north
JLabel statusBar = new JLabel("Welcome to PLabScript editor! Press File>New to create a new file or go to File>Open to open an existing one.");
statusBar.setOpaque(true);
statusBar.setBorder(BorderFactory.createLoweredSoftBevelBorder());
rootPanel.add(statusBar, "span, south"); //TODO Here is status bar added to the JFrame, it's docked south
documentSelector = new JTabbedPane(JTabbedPane.NORTH); //TODO JTabbedPane set so the tab chooser is on the top
rootPanel.add(documentSelector, "grow, push"); //TODO setup so it will take up all the remaining space
addNewDocument("Brand new document");
masterWindow.setContentPane(rootPanel);
masterWindow.setVisible(true);
}
}
class Document extends JScrollPane
{
private static final long serialVersionUID = 1L;
JPanel basePanel;
//methods
void addChapter(Chapter chapter, int index)
{
basePanel.add(chapter, "grow, push, h 2000", index-1); //TODO this here adds a chapter to the basePanel of the JScrollPane which is the a representative of a single document
//TODO it height is set to 2000 (and the problem occurs), but if you reduce it enough so it fits the window, problem will dissaper
}
//constructors
public Document()
{
super(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
getVerticalScrollBar().setUnitIncrement(20);
basePanel = new JPanel();
basePanel.setBackground(Color.RED);
basePanel.setLayout(new MigLayout("insets 0")); //TODO "insets 0" is so there is no border thingy around all of the child components
setViewportView(basePanel);
}
}
class Chapter extends JPanel
{
private static final long serialVersionUID = 1L;
//constructors
Chapter()
{
setLayout(new MigLayout("insets 0")); //TODO "insets 0" is so there is no border thingy around all of the child components
setBackground(Color.MAGENTA);
}
}
public class Main
{
public static ResourceBundle language;
static boolean setUpLAF()
{
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
try
{
UIManager.setLookAndFeel(info.getClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)
{
return false;
}
break;
}
}
return true;
}
public static void main(String[] args)
{
//SetUpLookAndFeel
setUpLAF();
//Display actual GUI
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new DisplayGUI();
}
});
}
}
Line 88 should read:
basePanel.add(chapter, "grow, push", index-1); //TODO this here adds a chapter to the basePanel of the JScrollPane which is the a representative of a single document
Line 100 should read:
basePanel.setLayout(new MigLayout("fill,insets 0")); //TODO "insets 0" is so there is no border thingy around all of the child components
Try this.
I am creating a Swing Application. I have one main JFrame and a JDesktopPane. I added one button and one label on main frame. But if I open any JInternalFrame on Main Frame button and label covers the internal frame.
(JButtonand JLabel appear foreground of JInternalFrame). If I click internal frame button go to background.
Can you help to solve this?
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class MainFrame {
JFrame frame1 ;
JDesktopPane desktop ;
public MainFrame () {
frame1 = new JFrame("EMPLOYEE LEAVE TRACKER");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setExtendedState(Frame.MAXIMIZED_BOTH);
frame1.repaint();
desktop = new JDesktopPane(); //Creates a new JDesktopPane.
frame1.setContentPane(desktop);
frame1.setSize(900,700);
frame1.setVisible(true);
desktop.setBackground(Color.DARK_GRAY );
//Creates a JLabel on JDesktopPane.
JLabel label1 = new JLabel("EMPLOYEE LEAVE TRACKER", SwingConstants.CENTER);
label1.setFont(new Font("SansSerif",Font.ITALIC + Font.BOLD,54));
label1.setBounds(new Rectangle(new Point(275, 100),label1.getPreferredSize()));
//Creates a JButon on JDesktopPane.
JButton Leave = new JButton("Leave Management");
Leave.setHorizontalTextPosition(JButton.CENTER);
Leave.setBounds(new Rectangle(new Point(700,200),Leave.getPreferredSize()));
Leave.setSize(300, 300);
Leave.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
frame1.add(LeaveManagment());
}
});
//Look and Feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
desktop.add(Leave);
desktop.add(label1);
}
//Creating JInternalFrame
public JInternalFrame LeaveManagment(){
final JInternalFrame employeeFrame = new JInternalFrame("LEAVE M" +
"ANAGEMNT", true, true, true, true);
employeeFrame.getContentPane().setBackground(Color.white);
employeeFrame.setSize(900,700);
employeeFrame.setVisible(true);
employeeFrame.setMaximizable(true);
employeeFrame.setResizable(true);
JComponent c = (JComponent)
employeeFrame.getContentPane();
c.setLayout(new FlowLayout());
return employeeFrame;
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame ();
}
});
}}
From the sound of it, you've added the buttons to the JDesktopPane.
The desktop pane is a type of JLayeredPane, this allows you to place components on, we'll, layers.
While this is a neat feature, IMHO, only JInternalFrames and the occasional special "window" should appear on the desktop (although the desktop manager does use a type of button to represent minimised windows)
Personally, I'd place the buttons also where, not on the desktop.
Take a look at How to Use Internal Frames and How to use Layered Pane
MadProgrammer has it right. One solution is to add your components to the appropriate JLayeredPane layer. i.e.,
// Note name change of JButton to adhere to Java naming standards:
desktop.add(leaveManagementBtn, JLayeredPane.DEFAULT_LAYER);
desktop.add(label1, JLayeredPane.DEFAULT_LAYER); // note layer component being added to
and,
public void actionPerformed(java.awt.event.ActionEvent e) {
// again method name capitalization changed to adhere to standard
// again, component added to appropriate layer
frame1.add(leaveManagment(), JLayeredPane.PALETTE_LAYER);
}
Again, MadProgrammer is right, the buttons should not be on the JDesktopFrame but on a button bar off of the desktop. I recommend that you accept his answer.