I've got an application that uses custom buttons all over the place for text and icons. Works great for windows and linux, but now OSX users are complaining. Text doesn't display on the mac, just '...'. The code seems simple enough, but I'm clueless when it comes to macs. How can I fix this?
Test case:
package example.swingx;
import example.utils.ResourceLoader;
import com.xduke.xlayouts.XTableLayout;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import java.awt.*;
import java.awt.event.ActionEvent;
public class SmallButton extends JButton {
private static ComponentUI ui = new SmallButtonUI();
public SmallButton() {
super();
/* final RepaintManager repaintManager = RepaintManager.currentManager(this);
repaintManager.setDoubleBufferingEnabled(false);
setDebugGraphicsOptions(DebugGraphics.FLASH_OPTION);*/
}
public SmallButton(AbstractAction action) {
super(action);
}
public SmallButton(String text) {
super(text);
}
public SmallButton(Icon icon) {
super(icon);
}
public void updateUI() {
setUI(ui);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel buttonPanel = new JPanel(new XTableLayout());
SmallButton firstSmallButton = new SmallButton("One");
SmallButton secondSmallButton = new SmallButton("Two");
SmallButton thirdSmallButton = new SmallButton();
ImageIcon cameraIcon = (ImageIcon) ResourceLoader.getIcon("camera");
SmallButton fourth = new SmallButton();
fourth.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("Fourth button pressed!");
}
});
fourth.setIcon(cameraIcon);
buttonPanel.add(firstSmallButton, "+");
buttonPanel.add(secondSmallButton, "+");
buttonPanel.add(thirdSmallButton, "+");
buttonPanel.add(fourth, "+");
final Container container = frame.getContentPane();
container.add(buttonPanel);
frame.pack();
frame.setVisible(true);
}
}
UI:
package example.swingx;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
public class SmallButtonUI extends BasicButtonUI {
private static final Color FOCUS_COLOR = new Color(0, 0, 0);
private static final Color BACKGROUND_COLOR = new Color(173, 193, 226);
private static final Color SELECT_COLOR = new Color(102, 132, 186);
private static final Color DISABLE_TEXT_COLOR = new Color(44, 44, 61);
private static final Insets DEFAULT_SMALLBUTTON_MARGIN = new Insets(2, 4, 2, 4);
private final static SmallButtonUI smallButtonUI = new SmallButtonUI();
public static ComponentUI createUI(JComponent component) {
return smallButtonUI;
}
protected Color getSelectColor() {
return SELECT_COLOR;
}
protected Color getDisabledTextColor() {
return DISABLE_TEXT_COLOR;
}
protected Color getFocusColor() {
return FOCUS_COLOR;
}
public void paint(Graphics g, JComponent c) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
super.paint(g, c);
}
protected void paintButtonPressed(Graphics graphics, AbstractButton button) {
if (button.isContentAreaFilled()) {
Dimension size = button.getSize();
graphics.setColor(getSelectColor());
graphics.fillRect(0, 0, size.width, size.height);
}
}
public Dimension getMinimumSize(JComponent component) {
final AbstractButton button = ((AbstractButton) component);
// Handle icon buttons:
Icon buttonIcon = button.getIcon();
if (buttonIcon != null) {
return new Dimension(
buttonIcon.getIconWidth(),
buttonIcon.getIconHeight()
);
}
// Handle text buttons:
final Font fontButton = button.getFont();
final FontMetrics fontMetrics = button.getFontMetrics(fontButton);
final String buttonText = button.getText();
if (buttonText != null) {
final int buttonTextWidth = fontMetrics.stringWidth(buttonText);
return new Dimension(buttonTextWidth + 15,
fontMetrics.getHeight() + 5);
}
return null;
}
protected void installDefaults(AbstractButton button) {
super.installDefaults(button);
button.setMargin(DEFAULT_SMALLBUTTON_MARGIN);
button.setBackground(getBackgroundColor());
}
private Color getBackgroundColor() {
return BACKGROUND_COLOR;
}
public Dimension getPreferredSize(JComponent component) {
return getMinimumSize(component);
}
public Dimension getMaximumSize(JComponent component) {
return super.getMinimumSize(component);
}
public SmallButtonUI() {
super();
}
}
EDIT: After debugging, it seems getMinimumSize() is the same on both platforms. Also, when I stop on anywhere Graphics is used, it seems that the mac has a transY value of 47, while linux has 0. This 47 seems to feed into the clipping regions as well. Where could that be getting set?\
Your calculation of preferred size is incorrect.
BasicButtonUI uses SwingUtilities.layoutCompoundLabel, examined here. In a label, the ellipsis is added if the string is too long, but a button is typically sized to fit its entire text.
Absent a better understanding of your context, I would use a sizeVariant, shown below. I've also shown a simple BasicButtonUI example using a smaller, derived Font. The UI menu can be used in conjunction with Quaqua for testing.
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicButtonUI;
/**
* #see https://stackoverflow.com/a/14599176/230513
* #see https://stackoverflow.com/a/11949899/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(new Color(0xfff0f0f0));
f.setLayout(new GridLayout(0, 1));
f.add(createToolBar(f));
f.add(variantPanel("mini"));
f.add(variantPanel("small"));
f.add(variantPanel("regular"));
f.add(variantPanel("large"));
JPanel customPanel = new JPanel();
customPanel.add(createCustom("One"));
customPanel.add(createCustom("Two"));
customPanel.add(createCustom("Three"));
f.add(customPanel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static JPanel variantPanel(String size) {
JPanel variantPanel = new JPanel();
variantPanel.add(createVariant("One", size));
variantPanel.add(createVariant("Two", size));
variantPanel.add(createVariant("Three", size));
return variantPanel;
}
private static JButton createVariant(String name, String size) {
JButton b = new JButton(name);
b.putClientProperty("JComponent.sizeVariant", size);
return b;
}
private static JButton createCustom(String name) {
JButton b = new JButton(name) {
#Override
public void updateUI() {
super.updateUI();
setUI(new CustomButtonUI());
}
};
return b;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
private static class CustomButtonUI extends BasicButtonUI {
private static final Color BACKGROUND_COLOR = new Color(173, 193, 226);
private static final Color SELECT_COLOR = new Color(102, 132, 186);
#Override
protected void paintText(Graphics g, AbstractButton b, Rectangle r, String t) {
super.paintText(g, b, r, t);
g.setColor(SELECT_COLOR);
g.drawRect(r.x, r.y, r.width, r.height);
}
#Override
protected void paintFocus(Graphics g, AbstractButton b,
Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
super.paintFocus(g, b, viewRect, textRect, iconRect);
g.setColor(Color.blue.darker());
g.drawRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
}
#Override
protected void paintButtonPressed(Graphics g, AbstractButton b) {
if (b.isContentAreaFilled()) {
g.setColor(SELECT_COLOR);
g.fillRect(0, 0, b.getWidth(), b.getHeight());
}
}
#Override
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
b.setFont(b.getFont().deriveFont(11f));
b.setBackground(BACKGROUND_COLOR);
}
public CustomButtonUI() {
super();
}
}
private static JToolBar createToolBar(final Component parent) {
final UIManager.LookAndFeelInfo[] available =
UIManager.getInstalledLookAndFeels();
List<String> names = new ArrayList<String>();
for (UIManager.LookAndFeelInfo info : available) {
names.add(info.getName());
}
final JComboBox combo = new JComboBox(names.toArray());
String current = UIManager.getLookAndFeel().getName();
combo.setSelectedItem(current);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int index = combo.getSelectedIndex();
try {
UIManager.setLookAndFeel(
available[index].getClassName());
SwingUtilities.updateComponentTreeUI(parent);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
});
JToolBar bar = new JToolBar("L&F");
bar.setLayout(new FlowLayout(FlowLayout.LEFT));
bar.add(combo);
return bar;
}
}
Related
I'm a Windows user, and I have developed a small software to calculate few parameter based on some inputs. The GUI in Windows is displayed as expected, but in Mac OS it's different. Please let me know how to correct it. The code for the same is.
package home;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import java.awt.Component;
import java.awt.ComponentOrientation;
/**
* Home Page for the application.
* #author Harshit Rathore
*
*/
public class Home_Main {
private JFrame f;
private JXTabbedPane tabbedpane;
private ImageIcon icon_view, icon_analysis, icon_algo, icon_info, icon_sche_gen;
Schedule_Generation schedule_gen;
View_JPanel2D view2d;
View_JPanel3D view3d;
MapJPanel mapPanel;
Home_Main() {
f = new JFrame();
f.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
f.setTitle("Anti-Accidental Algorithm");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabbedpane = new JXTabbedPane(JTabbedPane.LEFT);
AbstractTabRenderer renderer = (AbstractTabRenderer)tabbedpane.getTabRenderer();
renderer.setPrototypeText("This text is a prototype->");
renderer.setHorizontalTextAlignment(SwingConstants.LEADING);
icon_view = new ImageIcon(this.getClass().getResource("/view_icon.png"));
icon_analysis = new ImageIcon(this.getClass().getResource("/analysis_icon.png"));
icon_algo = new ImageIcon(this.getClass().getResource("/algo_icon.png"));
icon_info = new ImageIcon(this.getClass().getResource("/info_icon.png"));
icon_sche_gen = new ImageIcon(this.getClass().getResource("/schedule_icon.png"));
mapPanel = new home.MapJPanel();
view2d = new home.View_JPanel2D();
view3d = new home.View_JPanel3D();
schedule_gen = new home.Schedule_Generation(view2d, view3d, mapPanel);
tabbedpane.addTab("Algorithm", icon_algo, new home.Algo_JPanel());
tabbedpane.addTab("<html>Schedule<br>Generation</html>", icon_sche_gen, schedule_gen);
tabbedpane.addTab("<html>View Data 2D<br>(Azimuth, Elevation)</html>", icon_view, view2d);
tabbedpane.addTab("<html>View Data 3D<br>(Azimuth, Elevation, Tilt)</html>", icon_view, view3d);
tabbedpane.addTab("MapPanel", icon_info, mapPanel);
tabbedpane.addTab("<html>Windload<br>Torque</html>", icon_analysis, new home.WindloadTorque());
f.getContentPane().add(tabbedpane);
f.setMinimumSize(new Dimension(1100, 800));
f.setSize(1600, 800);
f.setVisible(true);
f.setEnabled(true);
}
/**
* The main function of the software.
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Home_Main();
}
// custom tabbedpane
class JXTabbedPane extends JTabbedPane {
/**
*
*/
private static final long serialVersionUID = 1L;
private ITabRenderer tabRenderer = new DefaultTabRenderer();
public JXTabbedPane() {
super();
}
public JXTabbedPane(int tabPlacement) {
super(tabPlacement);
}
public JXTabbedPane(int tabPlacement, int tabLayoutPolicy) {
super(tabPlacement, tabLayoutPolicy);
}
public ITabRenderer getTabRenderer() {
return tabRenderer;
}
public void setTabRenderer(ITabRenderer tabRenderer) {
this.tabRenderer = tabRenderer;
}
#Override
public void addTab(String title, Component component) {
this.addTab(title, null, component, null);
}
#Override
public void addTab(String title, Icon icon, Component component) {
this.addTab(title, icon, component, null);
}
#Override
public void addTab(String title, Icon icon, Component component, String tip) {
super.addTab(title, icon, component, tip);
int tabIndex = getTabCount() - 1;
Component tab = tabRenderer.getTabRendererComponent(this, title, icon, tabIndex);
super.setTabComponentAt(tabIndex, tab);
}
}
interface ITabRenderer {
public Component getTabRendererComponent(JTabbedPane tabbedPane, String text, Icon icon, int tabIndex);
}
abstract class AbstractTabRenderer implements ITabRenderer {
private String prototypeText = "";
private Icon prototypeIcon = new ImageIcon(this.getClass().getResource("/view_icon.png"));
private int horizontalTextAlignment = SwingConstants.CENTER;
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public AbstractTabRenderer() {
super();
}
public void setPrototypeText(String text) {
String oldText = this.prototypeText;
this.prototypeText = text;
firePropertyChange("prototypeText", oldText, text);
}
public String getPrototypeText() {
return prototypeText;
}
public Icon getPrototypeIcon() {
return prototypeIcon;
}
public void setPrototypeIcon(Icon icon) {
Icon oldIcon = this.prototypeIcon;
this.prototypeIcon = icon;
firePropertyChange("prototypeIcon", oldIcon, icon);
}
public int getHorizontalTextAlignment() {
return horizontalTextAlignment;
}
public void setHorizontalTextAlignment(int horizontalTextAlignment) {
this.horizontalTextAlignment = horizontalTextAlignment;
}
public PropertyChangeListener[] getPropertyChangeListeners() {
return propertyChangeSupport.getPropertyChangeListeners();
}
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
return propertyChangeSupport.getPropertyChangeListeners(propertyName);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
PropertyChangeListener[] listeners = getPropertyChangeListeners();
for (int i = listeners.length - 1; i >= 0; i--) {
listeners[i].propertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
}
}
}
class DefaultTabRenderer extends AbstractTabRenderer implements PropertyChangeListener {
private Component prototypeComponent;
public DefaultTabRenderer() {
super();
prototypeComponent = generateRendererComponent(getPrototypeText(), getPrototypeIcon(),
getHorizontalTextAlignment());
addPropertyChangeListener(this);
}
private Component generateRendererComponent(String text, Icon icon, int horizontalTabTextAlignmen) {
JPanel rendererComponent = new JPanel(new GridBagLayout());
rendererComponent.setOpaque(false);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 4, 2, 4);
c.fill = GridBagConstraints.HORIZONTAL;
rendererComponent.add(new JLabel(icon), c);
c.gridx = 1;
c.weightx = 1;
rendererComponent.add(new JLabel(text, horizontalTabTextAlignmen), c);
return rendererComponent;
}
#Override
public Component getTabRendererComponent(JTabbedPane tabbedPane, String text, Icon icon, int tabIndex) {
Component rendererComponent = generateRendererComponent(text, icon, getHorizontalTextAlignment());
int prototypeWidth = prototypeComponent.getPreferredSize().width;
int prototypeHeight = prototypeComponent.getPreferredSize().height;
rendererComponent.setPreferredSize(new Dimension(prototypeWidth, prototypeHeight));
return rendererComponent;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("prototypeText".equals(propertyName) || "prototypeIcon".equals(propertyName)) {
this.prototypeComponent = generateRendererComponent(getPrototypeText(), getPrototypeIcon(),
getHorizontalTextAlignment());
}
}
}
}
The outputs are-
First one is from Windows (desired one) second one is from Mac OS(need modification).
Thank You
The reason for the buttons looking different is because of Java Swing's LAF (Look & Feel).
The Look and Feel is like the master “theme” for your Swing Application where it defines specific rules on how certain components should look, etc…
Java Swing on Windows looks different from on Unix & OSX is because there is a different provider for the LAF (known as LAF "metal")
You thus can pack a LAF library into your program, and you can find many here.
To call a theme to be used, you must place this before any GUI/Swing events are called (AKA repaints, component inits, etc.):
try {
UIManager.setLookAndFeel(myThemeLAF.class.getName());
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
Alternatively, you could override the individual paintComponent(Graphics g) methods.
This can be achieved either through anonymous classes or just having a class extend that object and override it from there:
#1 Anonymous Inner Classes
JPanel myPanel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//... draw stuffs
}
};
#2 Extending existing objects
public class MyPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// paint stuffs
}
}
In my java application, my objective is to display or output an image using MVC architecture. My java application is comprised of an imagecontroller(main), imageview, and image model. I am currently able to select an image, the compiler acknowledges where the image has been selected from in the c: drive however it does not output or display the image. Here is a copy of my code below:
package imagecontroller;
import javax.swing.SwingUtilities;
import java.io.File;
public class ImageController {
private final ImageModel model;
private final ImageView view;
public ImageController () {
this.view = new ImageView(this);
this.model = new ImageModel(this.view);
public static void launch () {
new ImageController();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ImageController::launch);
}
}
package imagecontroller;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;
public class ImageView extends JFrame{
private final ImageController controller;
public ImageView(ImageController controller) {
this.controller = controller;
JFileChooser Chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG Images", "jpg", "png");
Chooser.addChoosableFileFilter(filter);
Chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
Chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result
Chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
Chooser.setAcceptAllFileFilterUsed(true);
File selectedFile = Chooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle("ImageAnnotator");
frame.setVisible(true);
frame.setSize(new Dimension (500,500));
}
}
}
package imagecontroller;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
public class ImageModel extends JComponent {
private final ImageView view;
private BufferedImage image;
public ImageModel(ImageView view) {
this.view = view;
}
public void CustomComponent (File png) {
BufferedImage image = null;
setPreferredSize(new Dimension(400, 400));
try {
this.image = ImageIO.read(new File("640px-Pleiades_large.png"));
} catch (IOException x) {
JOptionPane.showMessageDialog(null, "Not an ImageFile, Please Select an Image");
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g = g.create();
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
int margin = 20;
int w = (getWidth() - (2 * margin + 2)) / 2;
int h = this.image.getHeight() * w / this.image.getWidth();
g.drawImage(image, h, h, WIDTH, HEIGHT, view);
}
}
The reason that the MVC pattern is called the MVC pattern is that the name suggests the order. In other words, create the model, then the view, then the controllers.
Here's an image display GUI I put together.
So, let's start with the model. For an image viewer GUI, the model is pretty simple.
public class ImageDisplayModel {
private BufferedImage image;
private File file;
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
The ImageDisplayModel class is a plain Java class that holds a BufferedImage and a File path. By saving the File path, the next time the user selects an image, the directory will be set to be the same as the last image.
The ImageDisplayModel class is an ordinary getter / setter class.
The next step is to create the view.
public class ImageDisplay implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ImageDisplay());
}
private ImageDisplayModel model;
private ImagePanel imagePanel;
private JFrame frame;
public ImageDisplay() {
this.model = new ImageDisplayModel();
}
#Override
public void run() {
frame = new JFrame("Image Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
imagePanel = new ImagePanel(model);
frame.add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem openitem = new JMenuItem("Open...");
openitem.addActionListener(new OpenFileListener(this, model));
filemenu.add(openitem);
menubar.add(filemenu);
return menubar;
}
public void updateImagePanel(int width, int height) {
imagePanel.setPreferredSize(width, height);
imagePanel.repaint();
frame.pack();
}
public JFrame getFrame() {
return frame;
}
}
We start the application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The view constructor instantiates the application model.
The JFrame code is in the run method.
The JMenuBar method allows us to select multiple images, one after the other.
The getFrame method allows the eventual controller class to access the JFrame instance. The updateImagePanel method allows the eventual controller class to update the image panel.
Next, we create the DrawingPanel class.
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private ImageDisplayModel model;
public ImagePanel(ImageDisplayModel model) {
this.model = model;
this.setPreferredSize(649, 480);
}
public void setPreferredSize(int width, int height) {
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = model.getImage();
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
}
Simple and straightforward. We draw the BufferedImage if one exists. We also adjust the size of the JPanel so that the image fits.
The only information that the DrawingPanel class needs is the model class. The drawing panel will draw the image. Period.
Finally, we create the controller class.
public class OpenFileListener implements ActionListener {
private ImageDisplay frame;
private ImageDisplayModel model;
public OpenFileListener(ImageDisplay frame, ImageDisplayModel model) {
this.frame = frame;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & PNG Images", "jpg", "png");
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File file = model.getFile();
if (file != null) {
chooser.setCurrentDirectory(file);
}
int result = chooser.showOpenDialog(frame.getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
model.setFile(selectedFile);
BufferedImage image;
try {
image = ImageIO.read(selectedFile);
model.setImage(image);
frame.updateImagePanel(image.getWidth(),
image.getHeight());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The controller class updates the model information and instructs the view to repaint itself. The controller isn't concerned with the view internals. All the controller needs to know is that the view can update.
Finally, here's the complete runnable code. I made the classes inner classes so I could post this code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
public class ImageDisplay implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ImageDisplay());
}
private ImageDisplayModel model;
private ImagePanel imagePanel;
private JFrame frame;
public ImageDisplay() {
this.model = new ImageDisplayModel();
}
#Override
public void run() {
frame = new JFrame("Image Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
imagePanel = new ImagePanel(model);
frame.add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem openitem = new JMenuItem("Open...");
openitem.addActionListener(new OpenFileListener(this, model));
filemenu.add(openitem);
menubar.add(filemenu);
return menubar;
}
public void updateImagePanel(int width, int height) {
imagePanel.setPreferredSize(width, height);
imagePanel.repaint();
frame.pack();
}
public JFrame getFrame() {
return frame;
}
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private ImageDisplayModel model;
public ImagePanel(ImageDisplayModel model) {
this.model = model;
this.setPreferredSize(649, 480);
}
public void setPreferredSize(int width, int height) {
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = model.getImage();
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
}
public class OpenFileListener implements ActionListener {
private ImageDisplay frame;
private ImageDisplayModel model;
public OpenFileListener(ImageDisplay frame, ImageDisplayModel model) {
this.frame = frame;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & PNG Images", "jpg", "png");
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File file = model.getFile();
if (file != null) {
chooser.setCurrentDirectory(file);
}
int result = chooser.showOpenDialog(frame.getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
model.setFile(selectedFile);
BufferedImage image;
try {
image = ImageIO.read(selectedFile);
model.setImage(image);
frame.updateImagePanel(image.getWidth(),
image.getHeight());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ImageDisplayModel {
private BufferedImage image;
private File file;
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
}
I really found this interesting and thought to explore it a little more. Taking pointers from The MVC pattern and Swing (which I suggest you read especially the accepted answer) lets try have a go.
Explanation:
Brief Summary of the code to follow (based off of the above link)
The LoginView. The view is simply your UI components, with getter methods for any components needed by the LoginController as well as implementing a PropertyChangeListener which is used by the view to receive PropertyChangeEvents which could be fired by our LoginController or LoginModel.
The LoginController The controller has access to both the view and the model. The controller sets up the necessary events on the views components and reacts to them by validating input from the view and then asks the model to do its job and potentially that will change its state. The controller takes your views actions and interprets them. If you click on a button, it's the controller's job to figure out what that means and how the model should be manipulated based on that action.
The controller may also ask the view to change it does this by subscribing the view (which implements PropertyChangeListener) to its SwingPropertyChangeSupport. When the controller receives an action from the view, in this case the Login button pressed it validates inputs from the view and fires the necessary validation errors (if any). It then calls the model to do the actual validation.
The LoginModel The controller calls methods on the model which intern notifies the view when its state has changed. When something changes in the model, based either on some action you took (like clicking a button) the model notifies the view that its state has changed through the same mechanism as the controller.
The view can also ask the model for state. The view gets the state it displays directly from the model. For instance, if we pass in a model instance to our view which already has authenticated set to true, you will immediately receive the message to say you are logged in (this has not been demonstrated here, but would entail passing the model into the views constructor and after initializing the initView() doing something like onAuthenticatedPropertyChange(model.isAuthenticated())).
Some extra information is both controller and model implement the observer pattern (as in the view observes changes to the controller and models in order to react to them)
The controller also does all model execution on a background thread via a SwingWorker, and all property change listeners are fired back on the EDT
Here is the code which demonstrates the above:
TestApp.java:
import javax.swing.SwingUtilities;
public class TestApp {
public TestApp() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGUI() {
LoginModel model = new LoginModel();
LoginView view = new LoginView();
LoginController controller = new LoginController(view, model);
}
}
LoginView.java:
import java.awt.Color;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class LoginView implements PropertyChangeListener {
private JFrame frame;
private JPanel loginPanel;
private JTextField usernameTextField;
private JTextField passwordTextField;
private JLabel errorLabel;
private JButton loginButton;
public LoginView() {
initView();
}
private void initView() {
frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginPanel = createLoginPanel();
frame.add(loginPanel);
frame.pack();
frame.setVisible(true);
}
private JPanel createLoginPanel() {
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
usernameTextField = new JTextField();
usernameTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
usernameTextField.setColumns(20);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordTextField = new JTextField();
passwordTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordTextField.setColumns(20);
loginButton = new JButton("Login");
loginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
errorLabel = new JLabel();
errorLabel.setForeground(Color.RED);
errorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
errorLabel.setVisible(false);
panel.add(usernameLabel);
panel.add(usernameTextField);
panel.add(passwordLabel);
panel.add(passwordTextField);
panel.add(errorLabel);
panel.add(loginButton);
return panel;
}
public JButton getLoginButton() {
return loginButton;
}
public JTextField getUsernameTextField() {
return usernameTextField;
}
public JTextField getPasswordTextField() {
return passwordTextField;
}
public JFrame getFrame() {
return frame;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
switch (propertyName) {
case "authenticated":
// authentication has finished lets do something
onAuthenticatedPropertyChange((Boolean) newValue);
break;
case "authenticating":
// lets disable the UI as we authenticate
errorLabel.setVisible(false);
disableLoginPanelComponents(true);
break;
case "usernameInvalid":
showError((String) newValue);
break;
case "passwordInvalid":
showError((String) newValue);
break;
}
}
private void onAuthenticatedPropertyChange(Boolean authenticated) {
if (authenticated == true) {
errorLabel.setVisible(false);
JOptionPane.showMessageDialog(frame, "You are in!");
} else {
showError("Invalid username or password!");
}
// re-enable components after authentication regadless of fail or pass
disableLoginPanelComponents(false);
}
private void showError(String error) {
errorLabel.setText(error);
errorLabel.setVisible(true);
}
private void disableLoginPanelComponents(boolean disable) {
for (int i = 0; i < loginPanel.getComponentCount(); i++) {
Component component = (Component) loginPanel.getComponent(i);
if (component instanceof JTextField || component instanceof JButton) {
((JComponent) loginPanel.getComponent(i)).setEnabled(!disable);
}
}
}
}
LoginController:
import java.awt.event.ActionEvent;
import javax.swing.SwingWorker;
import javax.swing.event.SwingPropertyChangeSupport;
public class LoginController {
private final SwingPropertyChangeSupport propertyChangeSupport;
private final LoginView view;
private final LoginModel model;
public LoginController(LoginView view, LoginModel model) {
this.view = view;
this.model = model;
propertyChangeSupport = new SwingPropertyChangeSupport(this, true);
initController();
}
private void initController() {
// make the view a listener of both the model and controller as both can send events which the view must react too
model.addPropertyChangeListener(view);
propertyChangeSupport.addPropertyChangeListener(view);
view.getLoginButton().addActionListener((ActionEvent e) -> {
// lets do some basic validation of username and password fields
String username = view.getUsernameTextField().getText();
String password = view.getPasswordTextField().getText();
// validate user input before sending it to the model (this is the contorllers job - besdoes business rules i..e username doesnt exist etc)
if (username.isEmpty()) {
propertyChangeSupport.firePropertyChange("usernameInvalid", null, "Username cannot be empty!");
return;
}
if (password.isEmpty()) {
propertyChangeSupport.firePropertyChange("passwordInvalid", null, "Password cannot be empty!");
return;
}
// call the model to login on a background thread as the model may query the db or hit an API etc
new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
model.login(username, password);
return null;
}
}.execute();
});
}
}
LoginModel.java:
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.SwingPropertyChangeSupport;
public class LoginModel {
private final SwingPropertyChangeSupport propertyChangeSupport;
private boolean authenticated;
public LoginModel() {
propertyChangeSupport = new SwingPropertyChangeSupport(this, true); // we pass in true to noifty observers on the Event Dispatch Thread
}
public void login(String username, String password) {
propertyChangeSupport.firePropertyChange("authenticating", null, true);
// lets simulate query a database or something for 3 seconds
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(LoginModel.class.getName()).log(Level.SEVERE, null, ex);
}
authenticated = username.equals("admin") && password.equals("password");
propertyChangeSupport.firePropertyChange("authenticated", null, authenticated);
}
public void addPropertyChangeListener(PropertyChangeListener prop) {
propertyChangeSupport.addPropertyChangeListener(prop);
}
public boolean isAuthenticated() {
return authenticated;
}
}
The above is generic and doesn't directly answer YOUR question but gives you an example of an MVC pattern in Swing.
Update:
Here is an example specific to your issue
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.filechooser.FileNameExtensionFilter;
public class TestApp {
public TestApp() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGUI() {
DisplayImageModel model = new DisplayImageModel();
DisplayImageView view = new DisplayImageView();
DisplayImageController controller = new DisplayImageController(view, model);
}
class DisplayImageView implements PropertyChangeListener {
private JFrame frame;
private ImagePanel imagePanel;
private JLabel imageLabel;
private JButton pickImageButton;
public DisplayImageView() {
initView();
}
private void initView() {
frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = createImagePanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private JPanel createImagePanel() {
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
pickImageButton = new JButton("Pick an image");
pickImageButton.setAlignmentX(Component.CENTER_ALIGNMENT);
imagePanel = new ImagePanel();
imagePanel.getPanel().setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(imagePanel.getPanel());
panel.add(pickImageButton);
return panel;
}
public JButton getPickAnImageButton() {
return pickImageButton;
}
public JLabel getImageLabel() {
return imageLabel;
}
public JFrame getFrame() {
return frame;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
switch (propertyName) {
case "image":
onImagePropertyChange((BufferedImage) newValue);
break;
}
}
private void onImagePropertyChange(BufferedImage image) {
imagePanel.setImage(image);
frame.pack();
}
}
class DisplayImageModel {
private final SwingPropertyChangeSupport propertyChangeSupport;
private BufferedImage image;
public DisplayImageModel() {
propertyChangeSupport = new SwingPropertyChangeSupport(this, true); // we pass in true to noifty observers on the Event Dispatch Thread
}
public void setImage(BufferedImage image) {
this.image = image;
propertyChangeSupport.firePropertyChange("image", null, image);
}
public void addPropertyChangeListener(PropertyChangeListener prop) {
propertyChangeSupport.addPropertyChangeListener(prop);
}
public BufferedImage getImage() {
return image;
}
}
class DisplayImageController {
private final SwingPropertyChangeSupport propertyChangeSupport;
private final DisplayImageView view;
private final DisplayImageModel model;
public DisplayImageController(DisplayImageView view, DisplayImageModel model) {
this.view = view;
this.model = model;
propertyChangeSupport = new SwingPropertyChangeSupport(this, true);
initController();
}
private void initController() {
// make the view a listener of both the model and controller as both can send events which the view must react too
model.addPropertyChangeListener(view);
propertyChangeSupport.addPropertyChangeListener(view);
view.getPickAnImageButton().addActionListener((ActionEvent e) -> {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & PNG Images", "jpg", "png");
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(view.getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
BufferedImage image;
try {
image = ImageIO.read(selectedFile);
model.setImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
class ImagePanel {
private final JPanel panel;
private BufferedImage image;
public ImagePanel() {
this.panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (image != null) {
return new Dimension(image.getWidth(), image.getHeight());
} else {
return new Dimension(200, 200);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
};
panel.setBorder(new LineBorder(Color.GRAY, 1));
}
public void setImage(BufferedImage image) {
this.image = image;
panel.revalidate();
panel.repaint();
}
public JPanel getPanel() {
return panel;
}
}
}
I just started using Java Swing, and I was going through the following post: Dynamic fields addition in java/swing form.
I implement the code in this post with some modification, and it worked fine. As mentioned in the post, JPanel is not resizing itself when we add more rows. Can someone throw more light on this issue with easy to understand explanation that how can we resize JPanel as soon as we hit +/- button? Here is the code :
Row class
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class Row extends JPanel {
private JTextField quantity;
private JTextField item;
private JTextField price;
private JButton plus;
private JButton minus;
private RowList parent;
public Row(String initialQuantity, String initalPrice, String initialItem, RowList list) {
this.parent = list;
this.plus = new JButton(new AddRowAction());
this.minus = new JButton(new RemoveRowAction());
this.quantity = new JTextField(10);
this.item = new JTextField(10);
this.price = new JTextField(10);
this.quantity.setText(initialQuantity);
this.price.setText(initalPrice);
this.item.setText(initialItem);
add(this.plus);
add(this.minus);
add(this.quantity);
add(this.item);
add(this.price);
}
public class AddRowAction extends AbstractAction {
public AddRowAction() {
super("+");
}
public void actionPerformed(ActionEvent e) {
parent.cloneRow(Row.this);
}
}
public class RemoveRowAction extends AbstractAction {
public RemoveRowAction() {
super("-");
}
public void actionPerformed(ActionEvent e) {
parent.removeItem(Row.this);
}
}
public void enableAdd(boolean enabled) {
this.plus.setEnabled(enabled);
}
public void enableMinus(boolean enabled) {
this.minus.setEnabled(enabled);
}
}
RowList class
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class RowList extends JPanel{
private List<Row> rows;
public RowList() {
this.rows = new ArrayList<Row>();
Row initial = new Row("1","0.00","", this);
//addHeaders();
//addGenerateBillButton();
addItem(initial);
}
public void addHeaders(){
JLabel qty = new JLabel("Quantity");
//qty.setBounds(10, 0, 80, 25);
add(qty);
JLabel item = new JLabel("Item");
//item.setBounds(70, 0, 80, 25);
add(item);
JLabel price = new JLabel("Price");
//price.setBounds(120, 0, 80, 25);
add(price);
}
public void addGenerateBillButton(){
JButton billGenerationButton = new JButton("Generate Bill");
add(billGenerationButton);
}
public void cloneRow(Row row) {
Row theClone = new Row("1","0.00","", this);
addItem(theClone);
}
private void addItem(Row row) {
rows.add(row);
add(row);
refresh();
}
public void removeItem(Row entry) {
rows.remove(entry);
remove(entry);
refresh();
}
private void refresh() {
revalidate();
repaint();
if (rows.size() == 1) {
rows.get(0).enableMinus(false);
}
else {
for (Row e : rows) {
e.enableMinus(true);
}
}
}
}
Main class
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Enter Items");
RowList panel = new RowList();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can call the pack() of the frame again.
Try this: Add this in your Row class
public class AddRowAction extends AbstractAction
{
public AddRowAction()
{
super("+");
}
public void actionPerformed(ActionEvent e)
{
parent.cloneRow(Row.this);
((JFrame) SwingUtilities.getRoot(parent)).pack(); // <--- THIS LINE
}
}
public class RemoveRowAction extends AbstractAction
{
public RemoveRowAction()
{
super("-");
}
public void actionPerformed(ActionEvent e)
{
parent.removeItem(Row.this);
((JFrame) SwingUtilities.getRoot(parent)).pack(); // <--- THIS LINE
}
}
You can get the root component (JFrame) using the SwingUtilities.getRoot(comp) from the child component and call the pack() method after your new Row is added to your RowList.
This would resize your JPanel. But your RowList will be horizontal. This is where LayoutManager comes into play.
You can know more about different LayoutManagers here.
To fix this problem, in your RowList panel, set your layout to:
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Within your refresh method call doLayout() method after revalidate()
my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame
I'm trying to show and hide a panel during run time, so I call the methods from another class:
Con.Action(1);
to this method:
public void Action(int whichPanel) {
if (whichPanel == 1) {
if (frame.Data.isVisible()) {
frame.Data.setVisible(false);
// frame.splitPaneSec.remove(frame.Data);
} else {
System.out.println(".....");
//frame.Data.setVisible(false);
frame.Data.setVisible(true);
//frame.getContentPane().validate();
//frame.revalidate();
//frame.repaint();
//frame.pack();
}
}
So far i'm able to hide a panel but I can't show it again once I hidden it.
I've tried many ways some of them are commented out.
Any help is appreciated, cheers
I think I would rather remove and add it back.
parent.remove(dataPanel);
parent.validate();
parent.repaint();
parent.add(dataPanel);
parent.validate();
parent.repaint();
I highly recommed you to use enums for Tasks like this:
public void Action(int whichPanel) {
if (whichPanel == 1) {}
//Better;
public void Action(enumType myPanel){
if(myPanel == enumType.LoginScreen){}
with `
public enum enumType
{
LoginScreen,EditScreen //...
}`
You can hide and show Enums if you perfom the setVisible method directly on the Panel you want to show:
public void showLoginScreen()
{
loginPanel.setVisible(true);
registerMenu.setVisible(false);
}
The issue was because after setting the component back to visible
it was required to GUIClass.splitPane.setDividerLocation(157);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class HidePanel extends JFrame {
private static final int PANEL_HEIGHT = 50;
private static final int INITIAL_PANEL_WIDTH = 50;
private static final int TIMER_INTERVAL = 1;
private static final int PIXEL_DELTA = 2;
private Dimension panelDimension = new Dimension(INITIAL_PANEL_WIDTH, PANEL_HEIGHT);
private int vertOffset = -PANEL_HEIGHT;
private Timer showTimer = new HidePanel.ShowPanelTimer();
private Timer hideTimer = new HidePanel.HidePanelTimer();
static JLayeredPane lpane = new JLayeredPane();
JPanel panel = new JPanel();
public HidePanel() {
setBackground(Color.BLACK);
setLayout(null);
panel.setBounds(1200, 50, 100, 600);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Hide"));
panel.add(new JButton("Click Me"));
lpane.add(panel);//, //new Integer(0), 0);
add(panel);
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
final int height = e.getY() - 100 ;
if (height < 50 && !showTimer.isRunning() && !panel.isVisible()) {
showTimer.start();
} else if (height > PANEL_HEIGHT + 5 && !hideTimer.isRunning() && panel.isVisible()) {
hideTimer.start();
}
}
});
}
public static void main(String args[]) {
HidePanel h = new HidePanel();
h.setSize(1350, 700);
h.setVisible(true);
h.add(lpane, BorderLayout.CENTER);
}
private void positionPanel(final int offset) {
int panelWidth = getWidth();
System.out.println(" offset = " + offset);
panelDimension.setSize(panelWidth, PANEL_HEIGHT);
//panel.setBounds(insets.left, offset + insets.top, size.width, size.height);
}
private class ShowPanelTimer extends Timer implements ActionListener {
ShowPanelTimer() {
super(TIMER_INTERVAL, null);
addActionListener(this);
}
public void start() {
vertOffset = -PANEL_HEIGHT;
panel.setVisible(true);
super.start();
}
public void actionPerformed(ActionEvent e) {
if (vertOffset <= 0) {
positionPanel(vertOffset);
} else {
showTimer.stop();
}
vertOffset += PIXEL_DELTA;
}
}
private class HidePanelTimer extends Timer implements ActionListener {
HidePanelTimer() {
super(TIMER_INTERVAL, null);
addActionListener(this);
}
public void stop() {
panel.setVisible(false);
super.stop();
}
public void actionPerformed(ActionEvent e) {
if (vertOffset >= (-PANEL_HEIGHT)) {
vertOffset -= PIXEL_DELTA;
positionPanel(vertOffset);
} else {
hideTimer.stop();
}
}
}
}