What did I wrong on importing a custom font? - java

So I want to use the ocr-a font for my Text in my little Brick Breaker Game.
I tried to import a font I downloaded as .ttf. Then I tried to use it on my JButton with "btn_StartGame.setFont(ocr);". But then when I try to run it the Font didn't change. Can somebody please help me. I'm still learning to code so if I can do something better just tell me.
This should only be something like a starting window and a game window where the actual game runs which is not created yet.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
public class BrickBreaker extends JFrame
{
Font ocr;
private javax.swing.JButton btn_StartGame;
public BrickBreaker()
{
components();
}
private void components()
{
try
{
ocr = Font.createFont(Font.TRUETYPE_FONT, new File("ocr-aregular.ttf")).deriveFont(100f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(ocr);
} catch(IOException | FontFormatException e)
{
}
JFrame menuFrame = new JFrame();
JFrame gameFrame = new JFrame();
ImageIcon frameIcon = new ImageIcon("C:/Users/xxx/Desktop/Programmieren/Java/Brick Breaker/BrickBreakerLogo.png");
menuFrame.setDefaultCloseOperation(menuFrame.EXIT_ON_CLOSE);
menuFrame.setPreferredSize(new Dimension(800, 600));
menuFrame.setLocationRelativeTo(null);
menuFrame.setTitle("Menu");
menuFrame.setIconImage(frameIcon.getImage());
menuFrame.setResizable(false);
menuFrame.getContentPane().setBackground(Color.gray);
menuFrame.pack();
menuFrame.setVisible(true);
gameFrame.setIconImage(frameIcon.getImage());
gameFrame.setDefaultCloseOperation(gameFrame.EXIT_ON_CLOSE);
gameFrame.setLocationRelativeTo(null);
gameFrame.setTitle("Brick Breaker");
gameFrame.setPreferredSize(new Dimension(800, 600));
gameFrame.setResizable(false);
gameFrame.getContentPane().setBackground(Color.gray);
gameFrame.pack();
gameFrame.setVisible(false);
btn_StartGame = new JButton();
btn_StartGame.setText("Start Game");
btn_StartGame.setFont(ocr);
btn_StartGame.setBounds(250, 400, 300, 100);
btn_StartGame.setBackground(Color.black);
btn_StartGame.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent evt)
{
menuFrame.setVisible(false);
gameFrame.setVisible(true);
}
});
menuFrame.getContentPane().setLayout(null);
menuFrame.getContentPane().add(btn_StartGame);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new BrickBreaker().setVisible(true);
}
});
}
}

Related

Java Swing loading image from file chooser not displaying

This is for a class assignment. I am supposed to load a file and display it on my Swing application.
I followed the process from the notes but they were vague, I also used other stackoverflow posts, but I am not able to get this to work. When I load an image the program does not crash, but nothing displays.
-Do I have to repaint or refresh the file after the image is loaded? I tried that but it did not work. what am I doing wrong? The repaint method is commented.
import java.awt.FlowLayout;
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.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Part1 {
public static File selectedFile;
public static void main(String[] args) {
JFrame frame = buildFrame();
JButton button = new JButton("Select File");
frame.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
selectedFile = fileChooser.getSelectedFile();
CardImagePanel image = new CardImagePanel(selectedFile);
frame.add(image);
// frame.repaint();
}
}
});
}
private static JFrame buildFrame()
{
JFrame frame = new JFrame();
frame.setSize(1000,1000);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
return frame;
}
}
class CardImagePanel extends JPanel {
private BufferedImage image;
public CardImagePanel(File newImageFile)
{
try {
image = ImageIO.read(newImageFile);
} catch (IOException e){
e.printStackTrace();}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 500, 500, this);
}
}
As was mentioned, you need to call frame.revalidate(); after you add the new component.
You also should call image.setPreferredSize(new Dimension(500, 500)); or similar to ensure that your image isn't tiny.

why BufferedImage does not show full image in JLabel?

I am getting files from JFileChooser and showing them by reading with BufferedImage and putting in JLabels but there is a problem that my images are not completely shown in JLabels. Here is my code
public class ImagePreview
{
JPanel PicHolder= new JPanel();
public ImagePreview()
{
JButton GetImages = new JButton("Browse Images");
GetImages.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
CreatePreviews();
};
});
PicHolder.add(GetImages);
JFrame MainFrame = new JFrame("Image Preview");
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().add(PicHolder);
MainFrame.pack();
MainFrame.setVisible(true);
}
public void CreatePreviews()
{
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
File[] selectedCarImages = chooser.getSelectedFiles();
for(int a=0; a<selectedImages.length; a++)
{
try
{
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
PicHolder.add(picLabel);
}
}
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}
When I run this code, it shows user selected images but they are kind of automatically croped and not showing completely in JLabels.
What's wrong here? Why JLabels do not show full images?
You're adding all the components and images to a single panel having the default FlowLayout. Instead, use GridLayout for the picture labels and add the browse button to the frame's default BorderLayout, as shown below.
As tested:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImagePreview {
JFrame mainFrame = new JFrame("Image Preview");
JPanel picHolder = new JPanel(new GridLayout(0, 1));
public ImagePreview() {
JButton getImages = new JButton("Browse Images");
getImages.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
CreatePreviews();
}
});
mainFrame.add(getImages, BorderLayout.NORTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new JScrollPane(picHolder));
mainFrame.pack();
mainFrame.setLocationByPlatform(true);
mainFrame.setVisible(true);
}
public void CreatePreviews() {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(mainFrame);
File[] selectedImages = chooser.getSelectedFiles();
for (int a = 0; a < selectedImages.length; a++) {
try {
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picHolder.add(picLabel);
mainFrame.pack();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}

Is the area too small for JPopupMenu?

In the last question I was asking the community why my JPopupMenu did not appear on the screen.
I was unable to come up with a simple , runnable, compilable example.
So, here is what I did for you guys:
Is the area too small to draw a popup?
I want my popup to be like this:
The code of what I did is visible in the first photo.
Code:
/* The old code entered here has been removed */
Complete code can be found here
edit 2
I copied the various JRadioButtonMenuItem and the setupJPopup() into a new file and ran. It works. Why doesn't it work in ScreenRecorder class?
Code
package demo;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class PopupTrial {
public PopupTrial(){
setupJPopup();
JFrame frame = new JFrame();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
}
frame.getContentPane().add(label);
label.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
frame.setVisible(true);
frame.setSize(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new PopupTrial();
}
});
}
public void setupJPopup(){
encodingGroup.add(avi);
encodingGroup.add(quicktime);
popup.add(avi);
popup.add(quicktime);
popup.addSeparator();
recordingAreaGroup.add(entireScreen);
recordingAreaGroup.add(custom);
popup.add(entireScreen);
popup.add(custom);
popup.addSeparator();
cursorGroup.add(selectBlackCursor);
cursorGroup.add(selectWhiteCursor);
cursorGroup.add(selectNoCursor);
selectCursor.add(selectBlackCursor);
selectCursor.add(selectWhiteCursor);
selectCursor.add(selectNoCursor);
popup.add(selectCursor);
popup.pack();
}
JLabel label = new JLabel("Click Me");
ButtonGroup recordingAreaGroup = new ButtonGroup();
ButtonGroup cursorGroup = new ButtonGroup();
ButtonGroup encodingGroup = new ButtonGroup();
JPopupMenu popup = new JPopupMenu();
JRadioButtonMenuItem avi = new JRadioButtonMenuItem("AVI",true);
JRadioButtonMenuItem quicktime = new JRadioButtonMenuItem("QuickTime",false);
JRadioButtonMenuItem entireScreen = new JRadioButtonMenuItem("Entire Screen",true);
JRadioButtonMenuItem custom = new JRadioButtonMenuItem("Custom...",false);
JMenuItem selectCursor = new JMenu("Select a cursor");
JRadioButtonMenuItem selectWhiteCursor = new JRadioButtonMenuItem("White Cursor",true);
JRadioButtonMenuItem selectBlackCursor = new JRadioButtonMenuItem("Black Cursor",false);
JRadioButtonMenuItem selectNoCursor = new JRadioButtonMenuItem("No Cursor",false);
}
No, the size of the JFrame isn't related to why the PopupMenu isn't showing. Here's an example showing something similar to what you want (and using similar methods) working:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenu extends Box{
Dimension preferredSize = new Dimension(400,30);
public PopupMenu(){
super(BoxLayout.Y_AXIS);
final JPopupMenu menu = new JPopupMenu("Options");
for(int i = 1; i < 20; i++)
menu.add(new JMenuItem("Option" + i));
JLabel clickMe = new JLabel("ClickMe");
clickMe.setAlignmentX(RIGHT_ALIGNMENT);
clickMe.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
menu.show(e.getComponent(), e.getX(), e.getY());
}});
add(clickMe);
}
public Dimension getPreferredSize(){
return preferredSize;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PopupMenu());
frame.validate();
frame.pack();
frame.setVisible(true);
}
}

Java swing radioButton with changing, clickable icon

Designing a questionary, the scope of answer can be elected by radioButtons.
To display a greater clickable area (the application is for touchscreen), I layed icon_1 over the radiobuttons.
Every mouseclick can change the displayed icon to icon_2 and permantly vice versa.
I am sorry, using
jRadioButtonActionPerformed
ImageIcon o_ButtonIcon = new ImageIcon ("....")
jRadioButton.setIcon(Icon m_ButtonIcon).
I get no changing, clickable image.
Can you please give me a helping hand?
Seems to be working fine.
Post an SSCCE to show specific problems.
Here is example ( i do not recommend getScaledInstance(..) just used it for quick example)
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class Test {
private ImageIcon ii1;
private ImageIcon ii2;
private JRadioButton jrb = new JRadioButton("Click me :)");
private JFrame frame = new JFrame();
public Test() {
try {
ii1 = new ImageIcon(ImageIO.read(new URL("http://cdn.macrumors.com/article/2010/09/03/145454-itunes_10_icon.jpg")).getScaledInstance(48, 48, Image.SCALE_SMOOTH));
ii2 = new ImageIcon(ImageIO.read(new URL("http://www.quarktet.com/Icon-small.jpg")).getScaledInstance(48, 48, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
initComponents();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jrb.setIcon(ii1);
jrb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (jrb.getIcon() == ii1) {
jrb.setIcon(ii2);
} else {
jrb.setIcon(ii1);
}
}
});
frame.add(jrb);
frame.pack();
frame.setVisible(true);
}
}

JLayeredPane formatting issue

I have a problem with my JLayeredPane, I am probably doing something incredibly simple but I cannot wrap my head around it. The problem i have is that all the components are merged together and have not order. Could you please rectify this as I have no idea. The order I am trying to do is have a layout like this
output
label1 (behind)
input (in Front)
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class window extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 7092006413113558324L;
private static int NewSize;
public static String MainInput;
public static JLabel label1 = new JLabel();
public static JTextField input = new JTextField(10);
public static JTextArea output = new JTextArea(main.Winx, NewSize);
public window() {
super("Satine. /InDev-01/");
JLabel label1;
NewSize = main.Winy - 20;
setLayout(new BorderLayout());
output.setToolTipText("");
add(input, BorderLayout.PAGE_END);
add(output, BorderLayout.CENTER);
input.addKeyListener(this);
input.requestFocus();
ImageIcon icon = new ImageIcon("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\.Satine\\img\\textbox.png", "This is the desc");
label1 = new JLabel(icon);
add(label1, BorderLayout.PAGE_END);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
try {
MainMenu.start();
} catch (IOException e1) {
System.out.print(e1.getCause());
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
And the main class.
import java.awt.Container;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class main {
public static int Winx, Winy;
private static JLayeredPane lpane = new JLayeredPane();
public static void main(String[] args) throws IOException{
Winx = window.WIDTH;
Winy = window.HEIGHT;
window Mth= new window();
Mth.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mth.setSize(1280,720);
Mth.setVisible(true);
lpane.add(window.label1);
lpane.add(window.input);
lpane.add(window.output);
lpane.setLayer(window.label1, 2, -1);
lpane.setLayer(window.input, 1, 0);
lpane.setLayer(window.output, 3, 0);
Mth.pack();
}
}
Thank you for your time and I don't expect the code to be written for me, all I want is tips on where I am going wrong.
I recommend that you not use JLayeredPane as the overall layout of your GUI. Use BoxLayout or BorderLayout, and then use the JLayeredPane only where you need layering. Also, when adding components to the JLayeredPane, use the add method that takes a Component and an Integer. Don't call add(...) and then setLayer(...).
Edit: it's ok to use setLayer(...) as you're doing. I've never used this before, but per the API, it's one way to set the layer.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class LayeredPaneFun extends JPanel {
public static final String IMAGE_PATH = "http://duke.kenai.com/" +
"misc/Bullfight.jpg";
public LayeredPaneFun() {
try {
BufferedImage img = ImageIO.read(new URL(IMAGE_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel backgrndLabel = new JLabel(icon);
backgrndLabel.setSize(backgrndLabel.getPreferredSize());
JPanel forgroundPanel = new JPanel(new GridBagLayout());
forgroundPanel.setOpaque(false);
JLabel fooLabel = new JLabel("Foo");
fooLabel.setFont(fooLabel.getFont().deriveFont(Font.BOLD, 32));
fooLabel.setForeground(Color.cyan);
forgroundPanel.add(fooLabel);
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JButton("bar"));
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JTextField(10));
forgroundPanel.setSize(backgrndLabel.getPreferredSize());
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(backgrndLabel.getPreferredSize());
layeredPane.add(backgrndLabel, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(forgroundPanel, JLayeredPane.PALETTE_LAYER);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new JScrollPane(new JTextArea("Output", 10, 40)));
add(layeredPane);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LayeredPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LayeredPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories