I want to add background in JFrame how could I? [duplicate] - java

This question already has answers here:
Setting background color for a JFrame
(14 answers)
Closed 2 years ago.
Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background.
what should I do can anyone help me?
public class Triangle {
JLabel l1;
public static void main(String[] args) {
new Triangle();
}
public Triangle() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(400,400);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Polygon poly;
{
poly = new Polygon(
new int[]{110, 150, 50},
new int[]{200, 0, 0},
3);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.blue);
g2.fill(poly);
g2.setColor(Color.red);
g2.fillRect(0,0,25,75);
g2.setColor(Color.green);
g2.fillOval(200,100,100,50);
g2.setColor(Color.green);
g2.fillOval(300,300,250,250);
}
}
}
Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background.
what should I do can anyone help me?

Set background color to the JPanel
Try this:
TestPane myPane = new TestPane();
myPane.setBackground(Color.green);
frame.add(myPane);

Related

How to make holes in a shape in Piccolo2D?

In main Java it supports "winding rule" which may help to make holes in the shapes.
Unfortunately, this concept is ignored in Piccolo2D:
public class Try_Holes_01 {
#SuppressWarnings("serial")
public static void main(String[] args) {
final Path2D path = new Path2D.Double(Path2D.WIND_EVEN_ODD);
//final Path2D path = new Path2D.Double(Path2D.WIND_NON_ZERO);
path.append(new Ellipse2D.Double(100,100,200,200), false);
path.append(new Ellipse2D.Double(120,120,100,100), false);
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.fill(path);
}
};
final PPath path_p = new PPath(path);
path_p.setPaint(Color.BLACK);
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new PFrame() {
#Override
public void initialize() {
getCanvas().getLayer().addChild(path_p);
}
};
}
}
So how to make holes inside Piccolo2D paths?
PPath maintains a private GeneralPath member for its operations. It is initialized with WIND_NON_ZERO. Luckily it can be accessed with PPath.getPathReference(). So this should do the trick:
path_p.getPathReference().setWindingRule(Path2D.WIND_EVEN_ODD);
Here is a result:

How to make a transparent JFrame but keep everything else the same?

I want to make the JFrame transparent, but the image on top of it to be non-transparent. This is what I have now:
Does anyone know a way to make only the JFrame transparent?
Here's my code:
import javax.swing.*;
import java.awt.*;
import com.sun.awt.AWTUtilities;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
public class SplashDemo extends JFrame
{
public SplashDemo()
{
setUndecorated(true);
setSize(200, 200);
add(new JLabel(new ImageIcon("puppy2.png")));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setOpacity(0.85f);
}
public static void main(String[] args)
{
new SplashDemo();
}
}
Basically, you need to make a transparent window and a translucent content pane. This will mean anything added to the content pane will continue to be rendered without additional alphering...
public class TranscluentWindow {
public static void main(String[] args) {
new TranscluentWindow();
}
public TranscluentWindow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JWindow frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new TranslucentPane());
frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png")))));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TranslucentPane extends JPanel {
public TranslucentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
}

How to put a label on the are inside the circle in a JFrame?

I am designing a DFA related program.. so I want to put stuffs like Q0 or Q1 inside the circles but I don't know how.. Can someone please look at my code and tell me how? If its possible to directly put a name that will appear inside the circles, it would be great because I think its hard to set location for a JLabel.. here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class midterm extends JFrame
{
JPanel mainpanel;
JPanel gamepanel;
JPanel controls;
ExitButtonListener end=new ExitButtonListener();
public midterm()
{
super("My DFA Design");
setSize(700,700);
setLocation(400,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
panel();
this.getContentPane().add(mainpanel);
this.pack();
setVisible(true);
setSize(400,400);
}
public static void main(String[] args)
{
midterm frame=new midterm();
}
void panel()
{
mainpanel=new JPanel();
mainpanel.setLayout(new BorderLayout());
gamepanel=new JPanel();
gamepanel.setBorder(BorderFactory.createTitledBorder("Deterministic Finite Automata"));
gamepanel.setLayout(new GridLayout(2,3));
controls = new JPanel();
controls.setLayout(new BorderLayout());
controls.setBorder(BorderFactory.createTitledBorder("Control"));
JButton newGame = new JButton("Reset");
newGame.addActionListener(new NewButtonListener());
controls.add(newGame, BorderLayout.NORTH);
JButton exitGame = new JButton("Exit");
exitGame.addActionListener(end);
controls.add(exitGame, BorderLayout.SOUTH);
mainpanel.add(gamepanel, BorderLayout.CENTER);
mainpanel.add(controls, BorderLayout.EAST);
mainpanel.setVisible(true);
q1 c1=new q1();
q2 c2=new q2();
q3 c3=new q3();
gamepanel.add(c1);
gamepanel.add(c2);
gamepanel.add(c3);
}
class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
class NewButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
}
}
class q1 extends JPanel
{
final int radius=25;
public void paint(Graphics gr)
{
setBackground(Color.black);
gr.drawOval((100/2-radius),(100/2-radius), radius*2, radius*2);
}
}
class q2 extends JPanel
{
final int radius=25;
public void paint(Graphics gr)
{
setBackground(Color.black);
gr.drawOval((95/2-radius),(100/2-radius), radius*2, radius*2);
}
}
class q3 extends JPanel
{
final int radius=25;
public void paint(Graphics gr)
{
setBackground(Color.black);
gr.drawOval((250/2-radius),(50/2-radius), radius*2, radius*2);
}
}
}
Possible, yes, recommended, maybe not...
public class TestLabel {
public static void main(String[] args) {
new TestLabel();
}
public TestLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
add(new CircleLable("1"));
add(new JLabel("What is the capital of SegWay?"));
}
}
public class CircleLable extends JLabel {
public CircleLable() {
init();
}
public CircleLable(String text) {
super(text);
init();
}
protected void init() {
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
setBorder(new EmptyBorder(2, 2, 2, 2));
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(size.width, size.height);
size.height = size.width;
return size;
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Insets insets = getInsets();
int width = (getWidth() - (insets.left + insets.right));
int height = getHeight() - (insets.top + insets.bottom);
int radius = Math.max(width, height);
int x = insets.left + ((width - radius) / 2);
int y = insets.top + ((height - radius) / 2);
g2d.drawOval(x, y, radius, radius);
super.paintComponent(g2d);
g2d.dispose();
}
}
}
The problem I have with this solution is there is to much that can go wrong. Adding a Icon, changing the text alignment ect could through it off.
Personally, I would simply use a custom JPanel and render the text my self (making sure that the component was transparent first), but that's just me...
#MadProgrammer idea is better, but you can use dingbats for circled numbers: ➀, ➁, ➂, …

Rotating a JTextField vertically

I've seen a number of questions that ask how to rotate a JLabel or image at an arbitrary angle. All I need to do is rotate my text field 90 degrees, but I haven't found an easier way specifically for that angle. I thought I copied the answers correctly, but my text field is not rotating.
Here's an SSCCE of what I'm doing:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class VerticalRotationSSCCE {
private static class VerticalTextField extends JTextField {
private static final long serialVersionUID = 1L;
public VerticalTextField(String text) {
super(text);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int cx = getWidth() / 2;
int cy = getHeight() / 2;
g2.rotate(1/2 * Math.PI, cx, cy);
super.paintComponent(g2);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.getContentPane().add(new VerticalTextField("Foo"));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
What am I missing from the answers on how to rotate components?
Actually, yes, it can be done, but will require some additional libraries and access to some source code which has vanished off the net.
Using JXLayer, it is possible to transform live components at runtime...
public class JLayerTransform {
public static void main(String[] args) {
new JLayerTransform();
}
public JLayerTransform() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ExamplePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ExamplePane extends JPanel {
private JSlider slider;
private FieldPane fieldPane;
private DefaultTransformModel transformModel;
public ExamplePane() {
setLayout(new BorderLayout());
slider = new JSlider(0, 360);
slider.setValue(0);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
transformModel.setRotation(Math.toRadians(slider.getValue()));
}
});
fieldPane = new FieldPane();
transformModel = new DefaultTransformModel();
transformModel.setRotation(Math.toRadians(0));
transformModel.setScaleToPreferredSize(true);
JXLayer<JComponent> rotatePane = TransformUtils.createTransformJXLayer(fieldPane, transformModel);
add(slider, BorderLayout.NORTH);
add(rotatePane);
}
}
public class FieldPane extends JPanel {
public FieldPane() {
setLayout(new GridBagLayout());
JTextField field = new JTextField(10);
field.setText("Hello world");
add(field);
}
}
}
Caveats
This requires JXLayer (I was using version 3), SwingX (I was using version 1.6.4) and Piet Blok's excellent examples, which no longer seem to be available on the net...
I've put all the source code of JXLayer (version 3) and Piet's examples into a single zip and I would suggest, if you are interested, you grab a copy and store it some where safe.
You can't usefully rotate interactive components without also transforming the mouse coordinates, but you can rotate the graphics context to render non-interactive components like JLabel, as shown here.
In your example, 1/2 * Math.PI != Math.PI / 2.

How to Remove JFrame Border as to Let an Image Touch The Edge

I had a friend make a background for the program I made so that it wouldn't look so plain, and I thought the best way to place the images would be to make a JLabel, fill it with an image, and set it to the size of the screen. This worked fine, except there is a small border around the JFrame and I can't get the JLabel to touch the edges of the frame. Thoughts? I have attached a picture.
public class ProgramDriver extends JFrame {
private JPanel contentPane;
private static CardLayout cardLayout;
private JTextField addGradeN;
private JTextField addGradeD;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProgramDriver frame = new ProgramDriver();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Global Variables
...
manager = new StateManager(gb);
//JFrame Settings
setTitle("Grade Book");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 656, 530);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
cardLayout = new CardLayout(0,0);
contentPane.setLayout(cardLayout);
setResizable(false);
//Home Panel
final JPanel Home = new JPanel();
contentPane.add(Home, "Home");
Home.setLayout(null);
JButton btnSeeGrades = new JButton("See Grades");
...
//Grades Panel
JPanel Grades = new JPanel();
contentPane.add(Grades, "Grades");
Grades.setLayout(null);'
The problem isn't with the JFrame, the problem is with your code. We can spend the rest of our natural life at guessing what's wrong or you can post some example code.
Now it's up to you, we can keep trying to throw wrong guess after wrong guess at you, frustrating us all, or you can help us help you...
Here are two examples I did. The first uses a JLabel as the primary content for a JPanel, where the child components are placed on it. Nice and simple.
The second uses a custom JPanel which paints the image onto the background of the component. I then use this to replace the frames content pane. This is a little more involved, but it has the added benefit of been easily updated (replacing the content pane won't effect the rest of the program)
Example 1: JLabel used as background
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LabelPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class LabelPane extends JPanel {
public LabelPane() {
BufferedImage bg = null;
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon(bg));
setLayout(new BorderLayout());
add(label);
label.setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
label.add(lblMessage);
}
}
}
Example 2: Image used as background, replacing content pane...
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class BackgroundPane extends JPanel {
private BufferedImage bg = null;
public BackgroundPane() {
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
add(lblMessage);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1153, 823);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
g.drawImage(bg, 0, 0, this);
}
}
}
}
To expand on Eng.Fouad's answer, you'll want to use the drawImage(...) method that takes 6 parameters, image, x and y location, image width and height, and image observer, and draw it like so from within a JPanel:
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
For example, my sscce:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ExpandingImage extends JPanel {
public static final String GUITAR = "http://duke.kenai.com/Oracle/OracleStrat.png";
BufferedImage img;
public ExpandingImage(String imgUrlPath) throws IOException {
URL imgUrl = new URL(imgUrlPath);
img = ImageIO.read(imgUrl);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
private static void createAndShowGui() {
ExpandingImage mainPanel;
try {
mainPanel = new ExpandingImage(GUITAR);
JFrame frame = new JFrame("ExpandingImage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit
I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present?
As an alternative, you can override the method paintComponent(Graphics g) of JPanel (the contentPane) and use drawImage() on the Graphics object g as in this example.
have you tried JFrame function setUndecorated() ?
Make the frame undecorated. frame.setUndecorated(true)
If you want to make it move, you can use the ComponentMover of the Java2S.
Make sure that it is undecorated before it is visible.
Next, use setContentPane(new JLabel(new ImageIcon("myimage.jpg")));
After, that you can add contents as usual.

Categories