Okay this is probably a stupid question but I am new to GUI's and Java in general. In my GUI that I have made what is my frame called because no where do I see JFrame. Or do I have to create a JFrame and put everything I have on that. I need a JFrame to do things like minimize the screen, change the icon etc. Thanks for any help!
private ImageIcon bgi;
private JLabel bgl;
private JButton startButton;
private JButton helpButton;
private JButton backButton;
private final Action action = new SwingAction();
public static void main(String[] args) throws MalformedURLException, IOException {
TwitterUnfollower gui = new TwitterUnfollower ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
gui.setSize(902, 305);
gui.setVisible(true);
gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
}
public TwitterUnfollower() throws MalformedURLException, IOException{
bgi = new ImageIcon(getClass().getResource("tu.png"));
getContentPane().setLayout(null);
BufferedImage img = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/start_zpsf3781681.png"));
//ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
startButton = new JButton("");
startButton.setIcon(new ImageIcon(img));
startButton.setBounds(22, 186, 114, 50);
getContentPane().add(startButton);
BufferedImage img2 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/help_zpsc4fad867.png"));
helpButton = new JButton("");
helpButton.setIcon(new ImageIcon(img2));
helpButton.setBounds(192, 186, 114, 50);
getContentPane().add(helpButton);
BufferedImage img3 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/back_zps9d62b65b.png"));
backButton = new JButton("");
backButton.setIcon(new ImageIcon(img3));
backButton.setBounds(105, 205, 82, 44);
backButton.setBorder(BorderFactory.createEmptyBorder());
backButton.setContentAreaFilled(false);
backButton.setVisible(false);
getContentPane().add(backButton);
bgl = new JLabel (bgi);
bgl.setBounds(0, 0, 886, 272);
getContentPane().add(bgl);
Events e = new Events();
startButton.addActionListener(e);
helpButton.addActionListener(e);
backButton.addActionListener(e);
}
}
I do have an action listener I deleted it from the code to make it shorter. And I know I should avoid null layouts but I am using WindowBuilder, and that will probably change. Thanks again!
Do you mean something like this:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TwitterUnfollower extends JFrame {
private ImageIcon bgi;
private JLabel bgl;
private JButton startButton;
private JButton helpButton;
private JButton backButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
TwitterUnfollower gui = new TwitterUnfollower();
gui.setTitle("Solid Cloud Inc - Twitter Unfolower");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
gui.pack();
gui.setVisible(true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public TwitterUnfollower() throws MalformedURLException, IOException {
bgi = new ImageIcon(ImageIO.read(new URL(
"http://content.mcfc.co.uk//~/media/Images/Home/News/Club%20news/2012/twitter%20background%20new.ashx")));
bgl = new JLabel(bgi);
bgl.setLayout(new BorderLayout());
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
getContentPane().add(bgl);
BufferedImage img = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/start_zpsf3781681.png"));
// ImageIcon start = new ImageIcon(getClass().getResource("start.png"));
startButton = getButton(img);
BufferedImage img2 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/help_zpsc4fad867.png"));
helpButton = getButton(img2);
BufferedImage img3 = ImageIO.read(new URL("http://i1344.photobucket.com/albums/p656/SolidCloudInc/back_zps9d62b65b.png"));
backButton = getButton(img3);
JPanel alignLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
alignLeftPanel.setOpaque(false);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0));
buttonPanel.setOpaque(false);
buttonPanel.add(startButton);
buttonPanel.add(helpButton);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
alignLeftPanel.add(buttonPanel);
bgl.add(alignLeftPanel, BorderLayout.SOUTH);
}
private JButton getButton(BufferedImage img) {
JButton button = new JButton(new ImageIcon(img));
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);
return button;
}
}
Important: rather use a LayoutManager than using null layout which will only get you in trouble.
Caveat: photobucket returns status 503 so I can no longer test this code.
Related
I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}
In the main class Practice extends JFrame, there are three classes UpperPanel, CenterPanel and LowerPanel that extend JPanel.
I'm going to put buttons on UpperPanel and LowerPanel, and put a image on CenterPanel, and print it in one frame.
However, when the image prints out, three Panels aren't printed. and when three Panels print out, the image isn't printed.
I think the problem is setContentPane(new ImagePanel()); when I enter this code (in CenterPanel), Only images are printed. The rest of the panels(Upper, Center, Lower) are not output.
(I have created a separate image output class(ImagePanel extends JPanel), but It's okay to delete this class. But I want to use paintComponent(Graphics g).
I'm sorry for my poor English, and Thank you for reading it
please help me
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Practice extends JFrame {
public int width = 480;
public int height = 720;
public Practice() {
setTitle("20201209");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
setSize(width,height);
c.add(new UpperPanel());
c.add(new CenterPanel());
c.add(new LowerPanel());
setVisible(true);
}
class UpperPanel extends JPanel {
public UpperPanel() {
JPanel UpperPanel = new JPanel();
UpperPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 25));
UpperPanel.setBackground(Color.MAGENTA);
UpperPanel.setBounds(0, 0, 480, 100);
getContentPane().add(UpperPanel);
JButton btnEnlarge = new JButton("1");
btnEnlarge.setFont(new Font("궁서체", Font.PLAIN, 20));
btnEnlarge.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnEnlarge);
JButton btnReduce = new JButton("2");
btnReduce.setFont(new Font("바탕체", Font.ITALIC, 20));
btnReduce.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnReduce);
JButton btnFit = new JButton("3");
btnFit.setFont(new Font("돋움체", Font.BOLD, 20));
btnFit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
UpperPanel.add(btnFit);
}
}
class CenterPanel extends JPanel{
public CenterPanel() {
JPanel CenterPanel = new JPanel();
CenterPanel.setLayout(null);
CenterPanel.setBackground(Color.YELLOW);
CenterPanel.setBounds(0, 100, 480, 500);
CenterPanel.setOpaque(true);
getContentPane().add(CenterPanel);
setContentPane(new ImagePanel()); // when I enter this code, Only images are printed. The rest of the panels(Upper, Center, Lower) are not output
}
}
class ImagePanel extends JPanel { //this class is for image printing on CenterPanel
private ImageIcon icon = new ImageIcon("images/1771211.jpg");
private Image img = icon.getImage();
public void paintComponent(Graphics g) { //I want to use this code
super.paintComponent(g);
g.drawImage(img, 10, 110, this);
}
}
class LowerPanel extends JPanel {
public LowerPanel() {
JPanel LowerPanel = new JPanel();
LowerPanel.setLayout(null);
LowerPanel.setBackground(Color.BLACK);
LowerPanel.setBounds(0, 600, 480, 120);
getContentPane().add(LowerPanel);
getContentPane().add(new MyButton());
}
}
class MyButton extends JLabel{ //this class is for a Button on LowerPanel
MyButton(){
JButton btn = new JButton("4");
btn.setBounds(10, 610, 460, 100);
btn.setHorizontalAlignment(SwingConstants.CENTER);
btn.setVerticalAlignment(SwingConstants.CENTER);
btn.setFont(new Font("돋움체", Font.BOLD, 50));
btn.setBackground(Color.WHITE);
btn.setForeground(Color.RED);
btn.setOpaque(true);
getContentPane().add(btn);
}
}
public static void main(String[] args) {
new Practice();
}
}
Don't extend JFrame class unnecessarily
Don't use a null/AbsoluteLayout rather use an appropriate LayoutManager
Don't call setBounds() or setSize() on components, if you use a correct layout manager this will be handled for you
Call JFrame#pack() before setting the frame to visible
All Swing components should be called on the EDT via SwingUtilities.invokeLater
Here is a small example of what you want to achieve
TestApp.java:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestApp {
BufferedImage image;
public TestApp() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGui() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load image
try {
image = ImageIO.read(new URL("https://i.stack.imgur.com/XNO5e.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestApp.class.getName()).log(Level.SEVERE, null, ex);
}
// upper panel
JPanel upperPanel = new JPanel(); // JPanels use FlowLayout by default
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
upperPanel.add(button1);
upperPanel.add(button2);
upperPanel.add(button3);
// center panel
JPanel centerPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
};
// lower panel
JPanel lowerPanel = new JPanel();
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
lowerPanel.add(button4);
lowerPanel.add(button5);
lowerPanel.add(button6);
frame.add(upperPanel, BorderLayout.NORTH); // JFrame uses BorderLayout by default
frame.add(centerPanel, BorderLayout.CENTER);
frame.add(lowerPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
I want to do the same like this:
Here's the code:
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
class QuizGUI {
public static void main(String args[]) {
JFrame frm = new JFrame("Simple Quiz");
frm.setLayout(null);
JLabel lbl1 = new JLabel("Which Animal can fly?");
JLabel lbl2 = new JLabel("You have selected: ");
JLabel lblOutput = new JLabel();
JRadioButton rCat = new JRadioButton("Cat");
JRadioButton rBird = new JRadioButton("Bird");
JRadioButton rFish = new JRadioButton("Fish");
ButtonGroup bg = new ButtonGroup();
bg.add(rCat);
bg.add(rBird);
bg.add(rFish);
lbl1.setBounds(0, 0, 200, 20);
rCat.setBounds(0, 20, 100, 20);
rBird.setBounds(0, 40, 100, 20);
rFish.setBounds(0, 60, 100, 20);
lbl2.setBounds(0, 80, 200, 20);
lblOutput.setBounds(0, 105, 200, 20);
frm.add(lbl1);
frm.add(rCat);
frm.add(rBird);
frm.add(rFish);
frm.add(lbl2);
frm.add(lblOutput);
rCat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rCat.isSelected()) {
lblOutput.setText("Cat can't fly, Try again.");
}
}
});
rBird.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rBird.isSelected()) {
lblOutput.setText("Bird can fly, Excellent.");
}
}
});
rFish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rFish.isSelected()) {
lblOutput.setText("Cat can't fly, Try again.");
}
}
});
frm.setVisible(true);
frm.setSize(350, 200);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The problem is, I want the colors of window like image the background is white and the background for choices is gray.
I tried frame.setBackground but doesn't work.
I tried some codes for another examples and the color was white. I don't know why the window is all gray like this:
From the code you posted in your question:
frm.setLayout(null);
This is not a good idea. I recommend always using a layout manager. JFrame is a top-level container. It has a content pane which, by default, is a JPanel. The default layout manager for the content pane is BorderLayout. You can refer to the source code for JFrame in order to confirm this.
In my opinion BorderLayout is suitable for your GUI. One JPanel is the NORTH component and it displays the question, namely Which Animal can fly?, the radio buttons are the CENTER component and the text You have selected: is the SOUTH panel.
Each JPanel can then have its own background color. I am using JDK 13 on Windows 10 and the default background color is gray. Hence, in the code below, I set the background color for the NORTH and SOUTH panels and leave the CENTER panel with its default background color.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
public class QuizGUI implements ActionListener, Runnable {
private static final String BIRD = "Bird";
private static final String CAT = "Cat";
private static final String FISH = "Fish";
private JFrame frame;
private JLabel resultLabel;
#Override // java.awt.event.ActionListener
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case BIRD:
resultLabel.setText(BIRD + " can fly. Excellent.");
break;
case CAT:
resultLabel.setText(CAT + " can't fly. Try again.");
break;
case FISH:
resultLabel.setText(FISH + " can't fly. Try again.");
break;
default:
resultLabel.setText(actionCommand + " is not handled.");
}
}
#Override // java.lang.Runnable
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
frame = new JFrame("Simple Quiz");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createQuestionPanel(), BorderLayout.PAGE_START);
frame.add(createChoicesPanel(), BorderLayout.CENTER);
frame.add(createOutcomePanel(), BorderLayout.PAGE_END);
frame.setSize(350, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createRadioButton(String text, ButtonGroup bg, JPanel panel) {
JRadioButton radioButton = new JRadioButton(text);
radioButton.addActionListener(this);
bg.add(radioButton);
panel.add(radioButton);
}
private JPanel createChoicesPanel() {
JPanel choicesPanel = new JPanel(new GridLayout(0, 1));
ButtonGroup bg = new ButtonGroup();
createRadioButton(CAT, bg, choicesPanel);
createRadioButton(BIRD, bg, choicesPanel);
createRadioButton(FISH, bg, choicesPanel);
return choicesPanel;
}
private JPanel createOutcomePanel() {
JPanel outcomePanel = new JPanel(new GridLayout(0, 1, 0, 5));
outcomePanel.setBackground(Color.WHITE);
JLabel promptLabel = new JLabel("You have selected:");
setBoldFont(promptLabel);
outcomePanel.add(promptLabel);
resultLabel = new JLabel(" ");
outcomePanel.add(resultLabel);
return outcomePanel;
}
private JPanel createQuestionPanel() {
JPanel questionPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
questionPanel.setBackground(Color.WHITE);
JLabel questionLabel = new JLabel("Which Animal can fly?");
setBoldFont(questionLabel);
questionPanel.add(questionLabel);
return questionPanel;
}
private void setBoldFont(JLabel label) {
Font boldFont = label.getFont().deriveFont(Font.BOLD);
label.setFont(boldFont);
}
public static void main(String[] args) {
String slaf = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(slaf);
}
catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
UnsupportedLookAndFeelException x) {
System.out.println("WARNING (ignored): Failed to set [system] look-and-feel");
x.printStackTrace();
}
EventQueue.invokeLater(new QuizGUI());
}
}
First create a private JPanel called contentPane in your QuizGUI class. Then in your main method, type:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frm.setContentPane(contentPane);
contentPane.setLayout(null);
then, change all frm.add() with contentPane.add()
I hope this helped!
I am trying to work with grid layout, and im trying to put few panels there that has some data, but nothing gets rendered at all.
Here is the current code that I have:
package main.cache.test;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImageView {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImageView window = new ImageView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ImageView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmSpitePicker = new JFrame("Title");
frmSpitePicker.setSize(658, 395);
frmSpitePicker.setResizable(false);
frmSpitePicker.setLocationRelativeTo(null);
frmSpitePicker.getContentPane().setLayout(null);
frmSpitePicker.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 35, 620, 303);
frmSpitePicker.getContentPane().add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
File file = new File("images/");
panel.setLayout(new GridLayout((file.listFiles().length / 6), 6));
int i = 0;
// getting files name from folder
for (String name : file.list()) {
JPanel panel_1 = new JPanel();
panel_1.setBounds(209, 362, 82, 87);
frmSpitePicker.getContentPane().add(panel_1);
panel_1.setLayout(null);
// create label
JLabel lblNewLabel = new JLabel((i++) + "");
lblNewLabel.setBounds(12, 13, 56, 16);
lblNewLabel.setIcon(new ImageIcon(new ImageIcon("images/" + name).getImage().getScaledInstance(8, 8, 1)));
lblNewLabel.setHorizontalTextPosition(JLabel.CENTER);
lblNewLabel.setVerticalTextPosition(JLabel.BOTTOM);
panel_1.add(lblNewLabel);
// create button
JButton btnNewButton = new JButton("btn");
btnNewButton.setBounds(12, 42, 58, 25);
panel_1.add(btnNewButton);
// add to the panel
panel.add(panel_1);
}
}
}
I don't know what is wrong with this, and why Jpanel when being added, it doesn't get rendered but when adding a JLabel would work.
Thanks in advance!
Using layouts correctly, we can easily get something like this:
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
public class ImageView {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
ImageView window = new ImageView();
} catch (Exception e) {
e.printStackTrace();
}
});
}
public ImageView() {
initialize();
}
private void initialize() {
int num = 32; // number of images to show..
JFrame frmSpitePicker = new JFrame("Title");
frmSpitePicker.setResizable(false);
JPanel panel = new JPanel(new GridLayout(0, 6));
JScrollPane scrollPane = new JScrollPane(panel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
frmSpitePicker.getContentPane().add(scrollPane);
for (int ii = 1; ii <= num; ii++) {
JPanel panel_1 = new JPanel(new BorderLayout());
// create label
JLabel lblNewLabel = new JLabel(ii + "");
lblNewLabel.setIcon(new ImageIcon(getImage()));
lblNewLabel.setHorizontalTextPosition(JLabel.CENTER);
lblNewLabel.setVerticalTextPosition(JLabel.BOTTOM);
panel_1.add(lblNewLabel, BorderLayout.CENTER);
// create button
JButton btnNewButton = new JButton("btn");
panel_1.add(btnNewButton, BorderLayout.PAGE_END);
// add to the panel
panel.add(panel_1);
// hack to ensure our scroll bar is active
// we require 3 rows to be visible..
if (ii==18) frmSpitePicker.pack();
}
frmSpitePicker.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Normally we'd call pack() here!
//frmSpitePicker.pack();
frmSpitePicker.setLocationRelativeTo(null);
frmSpitePicker.setVisible(true);
}
java.util.Random r = new java.util.Random();
private BufferedImage getImage() {
int s = 16;
BufferedImage bi = new BufferedImage(
s, s, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(new Color(
r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.fillRect(0, 0, s, s);
g.dispose();
return bi;
}
}
Note that I would tend to use a JList for this type of case. The panel_1 would become a renderer for a POJO what encapsulates the label and button. But the button might not be needed, in that a list can have listeners for selection and activation. If that's what the button does, it'd be redundant in a list, and lblNewLabel could replace the entire panel_1.
BTW - please make sure all resources needed, are available to run the code. When it comes to images, we might hot link (load by URL) to images available on the net1 or generate them in the code (as done here).
One way to get image(s) for an example is to hot link to images seen in this Q&A. E.G. This answer hot links to an image embedded in this question.
for my program I currently want to use the open button to open a JFileChooser and select an image and then draw it on the JPanel on the left side of the applet, I know that the file is being retrieved but when i go to repaint the graphics context nothing happens. Thanks in advance.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
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;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class FinalProject390 {
public static void main(String[] args) {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Final Project");
f.setSize(1025, 520);
f.add(new GraphicsPanel());
f.add(new MainPanel());
f.setVisible(true);
}
}
class MainPanel extends JPanel implements ActionListener {
JButton openButton = new JButton("Open");
JButton newButton = new JButton("New");
JButton saveButton = new JButton("Save");
JButton saveAsButton = new JButton("Save As");
JButton drawLineButton = new JButton("Draw Line");
JButton drawRectangleButton = new JButton("Draw Rectangle");
JButton drawOvalButton = new JButton("Draw Oval");
JButton drawArcButton = new JButton("Draw Arc");
JButton extractPixelDataButton = new JButton("Extract Pixel Data");
JButton convoluteButton = new JButton("Convolute");
JTextField xPosStartField = new JTextField("x-Position Start");
JTextField yPosStartField = new JTextField("y-Position Start");
JTextField xPosEndField = new JTextField("x-Position End");
JTextField yPosEndField = new JTextField("y-Position End");
JTextField angleStartField = new JTextField("Angle Start");
JTextField angleSizeField = new JTextField("Angle Size");
public MainPanel() {
openButton.setBounds(660, 50, 100, 30);
openButton.addActionListener(this);
newButton.setBounds(780, 50, 100, 30);
saveButton.setBounds(900, 50, 100, 30);
drawLineButton.setBounds(660, 110, 160, 30);
drawRectangleButton.setBounds(840, 110, 160, 30);
drawOvalButton.setBounds(660, 155, 160, 30);
drawArcButton.setBounds(840, 155, 160, 30);
extractPixelDataButton.setBounds(660, 220, 160, 30);
convoluteButton.setBounds(840, 220, 160, 30);
xPosStartField.setBounds(660, 280, 100, 30);
yPosStartField.setBounds(660, 320, 100, 30);
xPosEndField.setBounds(660, 380, 100, 30);
yPosEndField.setBounds(660, 420, 100, 30);
angleStartField.setBounds(900, 280, 100, 30);
angleSizeField.setBounds(900, 320, 100, 30);
setLayout(null);
setBackground(Color.green);
setBounds(641, 0, 370, 480);
add(openButton);
add(newButton);
add(saveButton);
add(drawLineButton);
add(drawRectangleButton);
add(drawOvalButton);
add(drawArcButton);
add(extractPixelDataButton);
add(convoluteButton);
add(xPosStartField);
add(yPosStartField);
add(xPosEndField);
add(yPosEndField);
add(angleStartField);
add(angleSizeField);
}
#Override
public void actionPerformed(ActionEvent e) {
javax.swing.JFileChooser fileChooser = new JFileChooser();
BufferedImage bin = null, bi = null;
GraphicsPanel gPanel = new GraphicsPanel();
fileChooser.setCurrentDirectory(new File(System
.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
try {
bin = ImageIO.read(new File(selectedFile.getAbsolutePath()));
} catch (IOException e1) {
e1.printStackTrace();
}
gPanel.setImg(bin);
}
}
}
class GraphicsPanel extends JPanel {
BufferedImage bi = null, bin = null;
public GraphicsPanel() {
setLayout(null);
setBackground(Color.blue);
setSize(640, 480);
setLocation(0, 0);
}
public void setImg(BufferedImage b) {
this.bi = b;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
}
This looks like a homework assignment, so rather than an outright answer with code, instead please consider the following:
In your method createAndShowGUI() you instantiate a GraphicsPanel object and add it to a JFrame
In your actionPerformed() method, you instantiate another GraphicsPanel object (which is never added to the JFrame) and you call setImage().
Your image does not display because the GraphicsPanel control that has been added to your JFrame is not the same GraphicsPanel control that you set the image on.
I hope this will be enough to help you fix your code.