I have two child panels and one parent panel (background). My goal is to resize JLabel icon in firstPanel, when main panel is resized. I tried to use StretchIcon, but it works only when adding JLabel icon to main.
My code now:
import darrylbu.icon.StretchIcon;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class Task {
JFrame frame;
JPanel main;
public static void main(String args[]) {
new Task();
}
public Task() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 400));
main = mainPanel();
frame.add(main);
main.add(firstPanel());
main.add(secondPanel());
frame.pack();
frame.setVisible(true);
}
private JPanel mainPanel(){
JPanel main_panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage background = null;
try {
background = ImageIO.read(new URL("https://jpegshare.net/images/17/b0/17b0bad019ea5e37c84a5147a33b0ce7.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(background, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
main_panel.setLayout(new OverlayLayout(main_panel));
main_panel.setLayout(new GridLayout(1, 2));
return main_panel;
}
private JPanel firstPanel() {
JPanel first_panel = new JPanel();
first_panel.setOpaque(false);
BufferedImage image = null;
try {
image = ImageIO.read(new URL("https://jpegshare.net/images/7a/f3/7af3bfc51cb1170be9f5655d643147d7.png"));
} catch (IOException e) {
e.printStackTrace();
}
StretchIcon img = new StretchIcon(image);
JLabel icon = new JLabel(img);
first_panel.add(icon);
first_panel.setLayout(getLayout());
return first_panel;
}
private JPanel secondPanel(){
JPanel second_panel = new JPanel() {
#Override
public Dimension getMaximumSize() {
return new Dimension(300, 400);
}
#Override
public void paintComponent(Graphics g) {
BufferedImage image = null;
try {
image = ImageIO.read(new URL("https://jpegshare.net/images/17/bc/17bc21f519133ca31f857a65c897925a.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(image, 0, 0,
getWidth() / 2, getHeight() / 2, this);
}
};
second_panel.setLayout(new BoxLayout(second_panel, BoxLayout.Y_AXIS));
String [] resources = {"flowers", "nyanko", "tutturu~"};
for(String s : resources){
JLabel label = new JLabel(0 + " " + s);
label.setFont(new Font("Serif", Font.BOLD, 18));
second_panel.add(label);
}
return second_panel;
}
private GridBagLayout getLayout() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, 1.0};
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0, 1.0};
return gridBagLayout;
}
}
You can solve this with one resize listener attached to main panel. I assume that you want to resize JLabel exactly how much you resized your main panel. Here is how you can achieve that:
private Dimension main_size = null; //Inital Dimension of main JPanel
main.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
//This method is called everytime main panel is resized
if((main_size==null) ||
(main_size.width==0 && main_size.height==0)) {
main_size=main.getSize();
}
updateJLabelSize(icon,e.getComponent().getSize());
}
});
//Method for updating JLabel size
private void updateJLabelSize(JLabel icon,Dimension newSize) {
int heightDifference = newSize.height - main_size.height;
int widthDifference = newSize.width - main_size.width;
icon.setSize(new Dimension(icon.getWidth() + widthDifference,
icon.getHeight()+heightDifference));
main_size = newSize;
}
Related
I have a JPanel with a JLabel which owns an Icon picture.
how do I set a transparent red color at the top of the whole JPanel (including JLabel Icon)?
I have the transparent backgriound color on for the panel but I want the whole panel including the picture and everything get this transparent color. something like a transparent colorful glass at the top of the JPanel
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TransparentJLabel {
private static final String IMAGE_PATH = "http://duke.kenai.com/Oracle/OracleStratSmall.png";
private static void createAndShowUI() {
JPanel panel = new JPanel();
panel.setBackground(Color.pink);
URL imageUrl;
try {
imageUrl = new URL(IMAGE_PATH);
BufferedImage image = ImageIO.read(imageUrl);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
panel.add(label);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("TransparentJLabel");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
If you just need a layered panel over the whole contentPane, a simple glassPane will do fine (override it's paintComponent(...) method). For example:
JPanel glassPane = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
glassPane.setOpaque(false);
frame.setGlassPane(glassPane);
frame.getGlassPane().setVisible(true);
However, if you want a layered panel over only one JPanel, I would use JLayer combined with LayerUI, as MadProgrammer already mentioned. You will need a custom LayerUI in which you override the paint(Graphics g, JComponent c) method. I know that sounds dangerous, but I honestly don't know of another way of doing it...
I've provided an example below, this is the output:
As you can see, panel1 (or more accurately, the JLayer) is slighty transparent (RGBA = "0, 100, 0, 100") and panel2 is normal.
Code:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class Example {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
public Example() {
JFrame frame = new JFrame("Example");
JPanel panel1 = new JPanel();
panel1.add(new JButton("Panel 1"));
MyLayerUI layerUI = new MyLayerUI();
JLayer<JPanel> panel1Layer = new JLayer<JPanel>(panel1, layerUI);
panel1.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (layerUI.hasOverlay()) {
layerUI.setOverlay(false);
} else {
layerUI.setOverlay(true);
}
panel1Layer.repaint();
}
});
JPanel panel2 = new JPanel();
panel2.add(new JButton("Panel 2"));
JPanel contentPane = new JPanel(new GridLayout(2, 1));
contentPane.add(panel1Layer);
contentPane.add(panel2);
frame.setContentPane(contentPane);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyLayerUI extends LayerUI<JPanel> {
private boolean overlay = true;
#Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (hasOverlay()) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(new Color(0, 100, 0, 100));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
}
public boolean hasOverlay() {
return overlay;
}
public void setOverlay(boolean overlay) {
this.overlay = overlay;
}
}
I have created a custom JSlider that is used to zoom in and out on an image. I want to add a scroll bar when the image becomes to large to fit into my 400x400 frame so that the user is able to pan across the image, there should not be a scroll bar if the image fits the frame. I am very new to Swing so any help would be greatly appreciated I cant seem to get anything to work.
public class GraphicsOnly extends JComponent implements ChangeListener {
JPanel gui;
/** Displays the image. */
JLabel imageCanvas;
Dimension size;
double scale = 1.0;
private BufferedImage image;
public GraphicsOnly() {
size = new Dimension(10,10);
setBackground(Color.black);
try {
image = ImageIO.read(new File("car.jpg"));
} catch (IOException ex) {
}
}
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
public void stateChanged(ChangeEvent e) {
int value = ((JSlider)e.getSource()).getValue();
scale = value/100.0;
repaint();
revalidate();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double x = (w - scale * imageWidth)/2;
double y = (h - scale * imageHeight)/2;
AffineTransform at = AffineTransform.getTranslateInstance(x,y);
at.scale(scale, scale);
g2.drawRenderedImage(image, at);
setImage(image);
}
public Dimension getPreferredSize() {
int w = (int)(scale*size.width);
int h = (int)(scale*size.height);
return new Dimension(w, h);
}
private JSlider getControl() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 500, 50);
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(25);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(this);
return slider;
}
public static void main(String[] args) {
GraphicsOnly app = new GraphicsOnly();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(app.getGui());
app.setImage(app.image);
// frame.getContentPane().add(new JScrollPane(app));
frame.getContentPane().add(app.getControl(), "Last");
frame.setSize(700, 500);
frame.setLocation(200,200);
frame.setVisible(true);
}
}
This version works. There were a number of problems with the attempt seen above, including that it was now mixing component painting with custom painting. I adapted the paintComponent method to instead paint a scaled image.
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class GraphicsOnly extends JComponent implements ChangeListener {
JPanel gui;
/**
* Displays the image.
*/
JLabel imageCanvas;
Dimension size;
double scale = 1.0;
private BufferedImage image;
public GraphicsOnly() {
size = new Dimension(10, 10);
setBackground(Color.black);
try {
image = ImageIO.read(new URL("http://i.stack.imgur.com/7bI1Y.jpg"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui == null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300, 100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
public void stateChanged(ChangeEvent e) {
int value = ((JSlider) e.getSource()).getValue();
scale = value / 100.0;
paintImage();
}
protected void paintImage() {
int w = getWidth();
int h = getHeight();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
BufferedImage bi = new BufferedImage(
(int)(imageWidth*scale),
(int)(imageHeight*scale),
image.getType());
Graphics2D g2 = bi.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
double x = (w - scale * imageWidth) / 2;
double y = (h - scale * imageHeight) / 2;
AffineTransform at = AffineTransform.getTranslateInstance(0, 0);
at.scale(scale, scale);
g2.drawRenderedImage(image, at);
setImage(bi);
}
public Dimension getPreferredSize() {
int w = (int) (scale * size.width);
int h = (int) (scale * size.height);
return new Dimension(w, h);
}
private JSlider getControl() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 500, 50);
slider.setMajorTickSpacing(50);
slider.setMinorTickSpacing(25);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(this);
return slider;
}
public static void main(String[] args) {
GraphicsOnly app = new GraphicsOnly();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(app.getGui());
app.setImage(app.image);
// frame.getContentPane().add(new JScrollPane(app));
frame.getContentPane().add(app.getControl(), "Last");
frame.setSize(700, 500);
frame.setLocation(200, 200);
frame.setVisible(true);
}
}
I created a simple frame program that includes a image. But the image don't have the same size as the frame. If i enlarge the frame the image size stays the same?
How can i make the image the same size as the frame?
Here is my current code:
JPanel panel1 = new JPanel();
ImageIcon image1 = new ImageIcon("C:\\Users\\Dark Mangetsu\\Downloads\\Ceng102_Lab10.1\\image\\flower.jpg");
JLabel label1 = new JLabel(image1);
panel1.add(label1);
Color color1 = new Color (200, 0 ,100);
panel1.setBorder(BorderFactory.createLineBorder(color1, 3));
JFrame f = new JFrame("Frame");
f.setLayout(new BorderLayout(5,5));
f.add((panel1),BorderLayout.WEST);
f.setSize(320,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You can paint the image instead of using a label.
ImageIcon icon = new ImageIcon("C:\\Users\\Dark Mangetsu\\Downloads\\Ceng102_Lab10.1\\image\\flower.jpg");
Image image = icon.getImage();
JPanel panel1 = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight());
}
};
Also not sure, but I think you may want to add the panel to the CENTER and not the west (if you want the image to be centered in the frame).
Also not, if you want a preferredSize for the panel, you will have to override the getPreferredSize() of the panel also.
JPanel panel1 = new JPanel() {
...
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 200);
}
};
Then you can just pack() the frame, which is preferred, instead of setting the size
f.pack();
//f.setSize(320, 200);
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundResize {
public TestBackgroundResize() {
JFrame frame = new JFrame();
frame.setContentPane(createBackgroundPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createBackgroundPanel() {
return new JPanel() {
BufferedImage image;
{
try {
image = ImageIO.read(getClass().getResource("/marioblobs/mario.png"));
} catch (IOException ex) {
Logger.getLogger(TestBackgroundResize.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 200);
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestBackgroundResize();
}
});
}
}
I think the code is missing call to pack() method.
Here is a sample code:
public class ImageToPanel {
public static void main(String[] args) {
ImageToPanel itp = new ImageToPanel();
itp.go();
}
private void go() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() { createAndShowGUI(); }
});
}
private void createAndShowGUI() {
JFrame f =new JFrame();
f.setLayout(new BorderLayout());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setPreferredSize(new Dimension(640,400));
JLabel label = new JLabel( new ImageIcon("wallpaper.jpg") );
f.add(label, BorderLayout.CENTER);
JButton button = new JButton("Quit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}
SCREENSHOT
In the screenshot below, a 1920x1200 wallpaper is constrained seamlessly in a 640x400 frame.
Tested on
Windows 7
Java 7
EDIT:
ImageIcon image1 = new ImageIcon("wallpaper.jpg");
JLabel label1 = new JLabel(image1);
Color color1 = new Color (200, 0 ,100);
label1.setBorder(BorderFactory.createLineBorder(color1, 3));
JFrame f = new JFrame("Frame");
f.setLayout(new BorderLayout(5,5));
f.add(label1,BorderLayout.WEST);
f.setSize(320,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Before resize
After resize
I couldn't explain the question in the title any better, so here goes -
I created a tiled background image. I then set the created background image to my JFrame. However, I added my JScrollPane to said background. Depending on the order I place my code in, 1 of two things will happen. When I have my JScrollPane like so -
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
public class TestingApp {
public static JFrame programFrame;
public static JLabel projectBackground;
public static JLabel projectLogo;
public static JPanel allContent;
public static JPanel fourRows;
public static JPanel centerPanel;
public static JScrollPane scrollPane;
// Tiled Background
public static void tiledBackground() {
#SuppressWarnings("serial")
class ImagePanel extends JPanel {
public Image image;
public boolean tile;
ImagePanel(Image image) {
this.image = image;
this.tile = true;
};
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int iw = image.getWidth(this);
int ih = image.getHeight(this);
if (iw > 0 && ih > 0) {
for (int x = 0; x < getWidth(); x += iw) {
for (int y = 0; y < getHeight(); y += ih) {
g.drawImage(image, x, y, iw, ih, this);
}
}
}
}
}
}
// Making the parts for the GUI
public static void createGUI() {
java.net.URL img1 = null;
try {
img1 = new URL("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSE6uHn-B_qKtLZOKjQNVeIxhOaxbmfio45VMUq-mVgGKvgmeghKw");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Image image = null;
try {
image = ImageIO.read(img1);
} catch (IOException e) {
e.printStackTrace();
}
// programFrame Title and Layout
programFrame = new JFrame("Organizer");
programFrame.setLayout(new BorderLayout());
Icon backgroundIcon = new ImageIcon(img1);
projectBackground = new JLabel(backgroundIcon);
// Logo JLabel
java.net.URL img2 = null;
try {
img2 = new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTvXxBQRsJ5NgSb8VOSNU_Qfom6HRV_crcazhD6bSZUh_ux3VHbgQ");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Icon logoIcon = new ImageIcon(img2);
projectLogo = new JLabel(logoIcon);
projectLogo.setBorder(new EmptyBorder(10, 10, 10, 10));
// New JPanel for GridLayouts to hold each JPanel with GridLayouts
fourRows = new JPanel(new GridLayout(1, 4));
fourRows.setLayout(new GridLayout());
fourRows.setOpaque(false);
fourRows.add(new JButton("Button"));
fourRows.add(new JButton("Button"));
fourRows.add(new JButton("Button"));
fourRows.add(new JButton("Button"));
// Makes the Initial BorderLayout (Using allContent JPanel)
allContent = new JPanel();
allContent.setLayout(new BorderLayout());
allContent.add(projectLogo, BorderLayout.NORTH);
allContent.setVisible(true);
allContent.setOpaque(false);
allContent.add(fourRows, BorderLayout.CENTER);
// Add ScrollPane
scrollPane = new JScrollPane(allContent);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
// JFrame programFrame Constructors
programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
programFrame.setLayout(new BorderLayout());
programFrame.setContentPane(new ImagePanel(image));
programFrame.add(scrollPane);
programFrame.pack();
programFrame.setVisible(true);
programFrame.setResizable(true);
programFrame.setSize(1280, 720);
programFrame.setLocationRelativeTo(null);
} // public static void createGUI() Closing
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
} // public void run() Closing
});
}
}
It doesn't scroll on the entire JFrame, just the contentStuff, and even then, it stretches beyond to the bottom of the content to where the scroll bar isn't there, and you can't scroll.
However, when I rearrange that code, and I put my
programFrame.setContentPane(new ImagePanel(image));
BEFORE
programFrame.add(scrollPane);
I just get the repeated background image, and no content.
EDIT - Added an SSCCE
EDIT2 - Here's a solution I was trying. I tried creating an empty panel to add in the content that should update based on JFrame size. Needless to say, it didn't work. Small snippet of the edited code, nothing else was changed -
// Makes the Initial BorderLayout (Using allContent JPanel)
allContent = new JPanel();
allContent.setLayout(new BorderLayout());
allContent.add(warlordsLogo, BorderLayout.NORTH);
allContent.setVisible(true);
allContent.setOpaque(false);
allContent.add(fourRows, BorderLayout.CENTER);
int widthForCenterPanel = programFrame.getWidth();
int heightForCenterPanel = programFrame.getHeight();
// Makes a Panel to add the ScrollPane to to center is properly
centerPanel = new JPanel();
centerPanel.setOpaque(false);
centerPanel.setBounds(0, 0, widthForCenterPanel, heightForCenterPanel);
centerPanel.add(allContent);
// Add ScrollPane
scrollPane = new JScrollPane(centerPanel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
EDIT 3 - Fixed my SSCCE. If you notice when you try it, it's dependent on how large the JPanel is, not the JFrame.
I'm trying to make my own custom border, and I have done this through overriding the paint function in the JFrame. The problem which I have run into, is the fact that paint is being called after the constructor, causing it to paint the window over my controls. Because of this, my table only appears when I happen to click on where it is in the JFrame. I was wondering if there is a way to make the paint function happen before my constructor, or if there is a better way to create a custom border. Here is my code:
public class GuiMain extends JFrame {
int posX=0, posY=0;
JTable serverList;
public GuiMain()
{
this.setUndecorated(true);
this.setLayout(new GridBagLayout());
serverList = new JTable(Variables.servers, Variables.serversHeader);
add(serverList);
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e)
{
posX = e.getX();
posY = e.getY();
}
});
this.addMouseMotionListener(new MouseAdapter(){
public void mouseDragged(MouseEvent evt)
{
if(posY <= 20) {
setLocation(evt.getXOnScreen()-posX, evt.getYOnScreen()-posY);
}
}
});
}
public void paint(Graphics g)
{
g.setColor(new Color(100, 100, 100));
g.fillRect(0, 0, Main.width, Main.height);
g.setColor(new Color(70, 70, 70));
g.fillRect(0, 0, Main.width, 20);
}
}
Any help is appreciated! Thanks!
You know that it is not the safest thing to do, overriding paint(...) of a top-level window. What type of "border" are you trying to create? Where is your call to super.paint(g);? Myself, I'd create my own class that extended the AbstractBorder class, and then would use that Border on a JPanel that is the JFrame's contentPane.
For example,
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
#SuppressWarnings("serial")
public class FrameEg extends JPanel {
public static final String FRAME_URL_PATH = "http://th02.deviantart.net/"
+ "fs70/PRE/i/2010/199/1/0/Just_Frames_5_by_ScrapBee.png";
public static final int INSET_GAP = 120;
private BufferedImage frameImg;
private BufferedImage smlFrameImg;
public FrameEg() {
try {
URL frameUrl = new URL(FRAME_URL_PATH);
frameImg = ImageIO.read(frameUrl);
final int smlFrameWidth = frameImg.getWidth() / 2;
final int smlFrameHeight = frameImg.getHeight() / 2;
smlFrameImg = new BufferedImage(smlFrameWidth, smlFrameHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics g = smlFrameImg.getGraphics();
g.drawImage(frameImg, 0, 0, smlFrameWidth, smlFrameHeight, null);
g.dispose();
int top = INSET_GAP;
int left = top;
int bottom = top;
int right = left;
Insets insets = new Insets(top, left, bottom, right);
MyBorder myBorder = new MyBorder(frameImg, insets);
JTextArea textArea = new JTextArea(50, 60);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
for (int i = 0; i < 300; i++) {
textArea.append("Hello world! How is it going? ");
}
setLayout(new BorderLayout(1, 1));
setBackground(Color.black);
Dimension prefSize = new Dimension(frameImg.getWidth(),
frameImg.getHeight());
JPanel centerPanel = new MyPanel(prefSize);
centerPanel.setBorder(myBorder);
centerPanel.setLayout(new BorderLayout(1, 1));
centerPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
MyPanel rightUpperPanel = new MyPanel(new Dimension(smlFrameWidth,
smlFrameHeight));
MyPanel rightLowerPanel = new MyPanel(new Dimension(smlFrameWidth,
smlFrameHeight));
top = top / 2;
left = left / 2;
bottom = bottom / 2;
right = right / 2;
Insets smlInsets = new Insets(top, left, bottom, right);
rightUpperPanel.setBorder(new MyBorder(smlFrameImg, smlInsets));
rightUpperPanel.setLayout(new BorderLayout());
rightLowerPanel.setBorder(new MyBorder(smlFrameImg, smlInsets));
rightLowerPanel.setBackgroundImg(createBackgroundImg(rightLowerPanel
.getPreferredSize()));
JTextArea ruTextArea1 = new JTextArea(textArea.getDocument());
ruTextArea1.setWrapStyleWord(true);
ruTextArea1.setLineWrap(true);
rightUpperPanel.add(new JScrollPane(ruTextArea1), BorderLayout.CENTER);
JPanel rightPanel = new JPanel(new GridLayout(0, 1, 1, 1));
rightPanel.add(rightUpperPanel);
rightPanel.add(rightLowerPanel);
rightPanel.setOpaque(false);
add(centerPanel, BorderLayout.CENTER);
add(rightPanel, BorderLayout.EAST);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private BufferedImage createBackgroundImg(Dimension preferredSize) {
BufferedImage img = new BufferedImage(preferredSize.width,
preferredSize.height, BufferedImage.TYPE_INT_ARGB);
Point2D center = new Point2D.Float(img.getWidth()/2, img.getHeight()/2);
float radius = img.getWidth() / 2;
float[] dist = {0.0f, 1.0f};
Color centerColor = new Color(100, 100, 50);
Color outerColor = new Color(25, 25, 0);
Color[] colors = {centerColor , outerColor };
RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
Graphics2D g2 = img.createGraphics();
g2.setPaint(paint);
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
g2.dispose();
return img;
}
private static void createAndShowGui() {
FrameEg mainPanel = new FrameEg();
JFrame frame = new JFrame("FrameEg");
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class MyPanel extends JPanel {
private Dimension prefSize;
private BufferedImage backgroundImg;
public MyPanel(Dimension prefSize) {
this.prefSize = prefSize;
}
public void setBackgroundImg(BufferedImage background) {
this.backgroundImg = background;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgroundImg != null) {
g.drawImage(backgroundImg, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
}
#SuppressWarnings("serial")
class MyBorder extends AbstractBorder {
private BufferedImage borderImg;
private Insets insets;
public MyBorder(BufferedImage borderImg, Insets insets) {
this.borderImg = borderImg;
this.insets = insets;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
g.drawImage(borderImg, 0, 0, c);
}
#Override
public Insets getBorderInsets(Component c) {
return insets;
}
}
Which would look like so: