GUI RadioButtonJPanel - java

I need to create a GUI that has red, green and blue radiobuttons. When a radiobutton is clicked they should cause a panel in the centre of the frame to change to the corresponding backcolour colour. Here is my code below: what am I doing wrong. Here is my code below(please help; it compiles but the frame appears tiny and displays nothing):
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RadioButtons extends JFrame implements ActionListener {
JFrame f;
JPanel panel = new JPanel();
JRadioButton rb1, rb2, rb3;
JButton b1;
JButton b2;
JButton b3;
public RadioButtons() {
f = new JFrame();
rb1 = new JRadioButton("Green");
//rb1 = new JLabel(, JLabel.RIGHT);
rb1.setBounds(100, 70, 100, 40);
rb2 = new JRadioButton("Red");
rb2.setBounds(100, 90, 100, 40);
//rb2 = new JLabel("Red", JLabel.RIGHT);
rb3 = new JRadioButton("Blue");
rb3.setBounds(100, 100, 100, 40);
//rb3 = new JLabel("Blue", JLabel.RIGHT);
ButtonGroup s1 = new ButtonGroup();
s1.add(rb1);
s1.add(rb2);
s1.add(rb3);
this.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
f.setTitle("GUI Background Changer");
b1 = new JButton("Change background color");
b1.setBounds(200, 200, 50, 50);
b1.addActionListener(this);
b2 = new JButton("Change background color");
b2.setBounds(200, 200, 50, 50);
b2.addActionListener(this);
b3 = new JButton("Change background color");
b3.setBounds(200, 200, 50, 50);
b3.addActionListener(this);
add(rb1);
add(rb2);
add(rb3);
f.add(panel);
//x.setDefaultCloseOperation(XFrame.EXIT_ON_CLOSE);
}//constructor
public static void main(String[] args) {
RadioButtons radiobuttons = new RadioButtons();
radiobuttons.setJpanelSize(200, 200, 50, 50);//setJPanelSize(200,200,50,50);
radiobuttons.setDefaultCloseOperation(EXIT_ON_CLOSE);
}// main
public void backgroundChanged(ActionEvent e) {
Color initialcolor1 = Color.RED;
Color initialcolor2 = Color.BLUE;
Color initialcolor3 = Color.GREEN;
if (rb1.isSelected()) {
panel.setBackground(initialcolor1);
}// if
else
if (rb2.isSelected()) {
panel.setBackground(initialcolor2);
}// else if
else {
panel.setBackground(initialcolor2);
}// else
}
public void setJpanelSize(int v, int w, int x, int y) {
}// setJPanel size
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}//class

it compiles but the frame appears tiny and displays nothing):
That is probably because you forgot to pack your JFrame after adding the components. Invoke pack() for your frame after adding the components.
You will also want to:
Call setVisible(true) after all other actions.
Prevent from using null layout.

Related

How can I make a set of images correspond to an array in a GUI?

I am trying to make a character generator in java swing. You click the generate button, and it randomly pulls two character names from an array and displays them as JLabels (newGenerate, newGenerate2) in the GUI (one name on top, and the other on the bottom). I would like for an image of the randomly chosen character to appear when their name is pulled. I have no clue how to do it. Forgive me if this doesn't make any sense, I am new to this.
import javax.swing.*;
import java.awt.*;
import java.util.Random;
import java.awt.event.*;
class Main implements ActionListener{
JFrame f = new JFrame("ℂ𝕙𝕒𝕣𝕒𝕔π•₯𝕖𝕣 π”Ύπ•–π•Ÿπ•–π•£π•’π•₯𝕠𝕣");
Random r = new Random();
JButton generate = new JButton("Generate");
JButton clear = new JButton("Clear");
JLabel newGenerate = new JLabel("Character", JLabel.CENTER);
JLabel newGenerate2 = new JLabel("Character", JLabel.CENTER);
Color custBlue = new Color(10, 63, 250);
Color custOrange = new Color(251,167,88);
Color saturatedCustOrange = new Color(254, 127, 46);
ImageIcon back_image = new ImageIcon("images/back_ground.jpg");
JLabel img2 = new JLabel(back_image);
ImageIcon wheel = new ImageIcon("images/loading_wheel.gif");
JLabel img = new JLabel(wheel);
String[] names1 = {"<html><p align='center'>Character1</p></html>", "<html><p align='center'>Character2</p></html>", "<html><p align='center'>Character3</p></html>", "<html><p align='center'>Character4</p></html>", "<html><p align='center'>Character6</p></html>", "<html><p align='center'>Character6</p></html>", "<html><p align='center'>Character7</p></html>", "<html><p align='center'>Character8</p></html>", "<html><p align='center'>Character9</p></html>",};
public static void main(String[] args) {
Main o = new Main();
o.gui();
}
public void gui(){
f.setSize(500, 400);
this.newGenerate.setBounds(250,190, 100, 40);
this.newGenerate.setForeground(saturatedCustOrange);
f.add(this.newGenerate);
this.newGenerate2.setBounds(250,10, 100, 40);
this.newGenerate2.setForeground(saturatedCustOrange);
f.add(this.newGenerate2);
this.generate.setBounds(28, 140, 120, 40);
generate.setFont(new Font("Arial", Font.BOLD, 16));
this.generate.setForeground(custOrange);
this.generate.setBackground(custBlue);
this.generate.addActionListener(this);
f.add(this.generate);
this.clear.setBounds(28, 190, 120, 40);
clear.setFont(new Font("Arial", Font.BOLD, 16));
this.clear.setForeground(custOrange);
this.clear.setBackground(custBlue);
this.clear.addActionListener(this);
f.add(this.clear);
img.setBounds(0, -10,500,400);
f.add(img);
img2.setBounds(0, -10,500,400);
f.add(img2);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == this.clear){
img.setVisible(true);
this.newGenerate.setText("Character");
this.newGenerate2.setText("Character");
}
else{
this.newGenerate.setText(this.returnChar());
this.newGenerate2.setText(this.returnChar());
img.setVisible(false);
}
}
public String returnChar() {
int ranNum = r.nextInt(this.names1.length);
return this.names1[ranNum];
}
}

Change the properties of a JPanel component through an action event

I'm trying to setup a system where when I press a button the JLabel text will change, but I can't seem to make it work. I've already tested that the action listener works by doing 'system.out.println("test");'. It works fine, but when trying to change a JComponent text it doesn't work. I've already searched for answers and found nothing that works.
Main class:
package com.fcs.app;
public class A {
public static void main(String args[]) {
window w = new window();
w.drawWindow();
}
}
JFrame and JPanel class:
package com.fcs.app;
import java.awt.*;
import javax.swing.*;
public class window extends JPanel {
JFrame jf = new JFrame();
JPanel jp = new JPanel();
JButton b1 = new JButton();
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JLabel plus = new JLabel();
JLabel equals = new JLabel();
JLabel rt = new JLabel();
int Result = 10;
public void drawWindow() {
//JFrame setup
jf.setSize(400, 400);
jf.setUndecorated(true);
jf.setLayout(null);
jf.setContentPane(jp);
jf.setLocation(100, 100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
//JPanel setup
jp.setSize(400, 400);
jp.setLocation(0, 0);
jp.setBackground(Color.WHITE);
jp.add(b1);
jp.add(tf1);
jp.add(tf2);
jp.add(plus);
jp.add(equals);
jp.add(rt);
jp.setLayout(null);
jp.setVisible(true);
//JButton setup
b1.setFont(new Font("Times", Font.PLAIN, 15));
b1.setText("Calculate!");
b1.setSize(100, 40);
b1.setLocation(150, 350);
b1.addActionListener(new Listener());
b1.setVisible(true);
//TextField 1 setup
tf1.setSize(120, 50);
tf1.setLocation(140, 20);
tf1.setFont(new Font("Times", Font.PLAIN, 25));
tf1.setHorizontalAlignment(JTextField.CENTER);
tf1.setVisible(true);
//TextField 2 setup
tf2.setSize(120, 50);
tf2.setLocation(140, 120);
tf2.setFont(new Font("Times", Font.PLAIN, 25));
tf2.setHorizontalAlignment(JTextField.CENTER);
tf2.setVisible(true);
//Plus sign Setup
plus.setSize(120, 50);
plus.setLocation(140, 70);
plus.setHorizontalAlignment(JLabel.CENTER);
plus.setFont(new Font("Times", Font.PLAIN, 40));
plus.setText("+");
plus.setVisible(true);
//Equals sign Setup
equals.setSize(120, 50);
equals.setLocation(140, 170);
equals.setHorizontalAlignment(JLabel.CENTER);
equals.setFont(new Font("Times", Font.PLAIN, 40));
equals.setText("=");
equals.setVisible(true);
//Result text
rt.setSize(400, 50);
rt.setLocation(0, 250);
rt.setHorizontalAlignment(JLabel.CENTER);
rt.setFont(new Font("Times", Font.PLAIN, 60));
rt.setText("");
rt.setVisible(true);
}
}
ActionListener class:
package com.fcs.app;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Listener implements ActionListener {
window w = new window();
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
w.rt.setText("Test");
}
}
You are creating new references of Window like window w = new window();
it will create a new instance of window and you are trying to change newly created window.
Try to pass the window object you have created before in window class or
implement an anonymous ActionListener in the window class.
b1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
rt.setText("Test");
}
}
});

Compiler Warning class uses unchecked or unsafe operations

My code is currently working fine, but whenever i compile, i get the Warning
C:\Users\etc\etc\FinalProject\AddItem.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.
Should I do something about it, and if so, what? if my debugging is right, it appears to be caused by the content pane properties.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.io.*;
class AddItem extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private JButton submitButton;
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
//variables
public static void main(String[] args)
{
AddItem ProjectFrame = new AddItem();
ProjectFrame.setVisible(true); // Display the frame
//for combobox
//new AddItem().setVisible(true);
}
public AddItem ( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(true);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("Add an item");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
Logo.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
setVisible(false);
FinalProject FP = new FinalProject();
FP.setVisible(true);
}
});
//set button properties
//for combobox
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(null); //ONLY PROBLEM WITH THIS IS GETTING THE SCREEN TO APPEAR AT CORRECT SIZE
String[] values = {"Computer", "Monitor", "Keyboard"};
final JComboBox b = new JComboBox(values);
b.setEditable(true);
add(b);
b.setBounds(300, 300, 100, 50); //this works
add(b);
submitButton = new JButton("Submit");
submitButton.setBounds(700,600, BUTTON_WIDTH, BUTTON_HEIGHT);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String item=b.getSelectedItem().toString();
}
});
contentPane.add(submitButton);
//pack(); //not quite sure what this is for, but it makes the window tiny, so i commented it out
setLocationRelativeTo(null); //positions window center on screen
}
public void actionPerformed(ActionEvent event) // Actions
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
}
}
you get the warning here I think:
final JComboBox b = new JComboBox(values);
to avoid this you have the following possibilities:
add SupressWarning above the JComboBox
#SuppressWarnings("unchecked")
final JComboBox b = new JComboBox(values);
or add SupressWarning above your method
#SuppressWarnings("rawtypes")
public AddItem ( )
or my favourite add the generic:
final JComboBox<Object> b = new JComboBox<Object>(values);

Inserting image through event handling?

I am encountering problems with event handling in java.
I want to add the image1 if button 1 is pressed, image2 if button 2 is pressed, et cetera.
This is my code till now; Can anyone help? This code doesn't compile.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ImageIcon;
public class MyPanel extends JPanel {
private JLabel jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JButton jcomp4;
private JButton jcomp5;
private JButton jcomp6;
private JButton jcomp7;
private JButton jcomp8;
private JButton jcomp9;
private ImageIcon image1;
private ImageIcon image2;
private ImageIcon image3;
private ImageIcon image4;
private ImageIcon image5;
private ImageIcon image6;
private ImageIcon image7;
private ImageIcon image8;
public MyPanel() {
//construct components
image1 = new ImageIcon(getClass().getResource("hang1.jpg"));
image2 = new ImageIcon(getClass().getResource("hang2.jpg"));
image3 = new ImageIcon(getClass().getResource("hang3.jpg"));
image4 = new ImageIcon(getClass().getResource("hang4.jpg"));
image5 = new ImageIcon(getClass().getResource("hang5.jpg"));
image6 = new ImageIcon(getClass().getResource("hang6.jpg"));
image7 = new ImageIcon(getClass().getResource("hang7.jpg"));
image8 = new ImageIcon(getClass().getResource("hang8.jpg"));
jcomp1 = new JLabel (image1);
jcomp2 = new JButton ("1");
jcomp3 = new JButton ("2");
jcomp4 = new JButton ("3");
jcomp5 = new JButton ("4");
jcomp6 = new JButton ("5");
jcomp7 = new JButton ("6");
jcomp8 = new JButton ("7");
jcomp9 = new JButton ("8");
//events
jcomp2.setActionCommand("1");
jcomp3.setActionCommand("2");
jcomp4.setActionCommand("3");
jcomp5.setActionCommand("4");
jcomp6.setActionCommand("5");
jcomp7.setActionCommand("6");
jcomp8.setActionCommand("7");
jcomp9.setActionCommand("8");
jcomp2.addActionListener(new ButtonClickListener());
jcomp3.addActionListener(new ButtonClickListener());
jcomp4.addActionListener(new ButtonClickListener());
jcomp5.addActionListener(new ButtonClickListener());
jcomp6.addActionListener(new ButtonClickListener());
jcomp7.addActionListener(new ButtonClickListener());
jcomp8.addActionListener(new ButtonClickListener());
jcomp9.addActionListener(new ButtonClickListener());
//adjust size and set layout
setPreferredSize(new Dimension(624, 537));
setLayout(null);
//add components
add(jcomp2);
add(jcomp3);
add(jcomp4);
add(jcomp5);
add(jcomp6);
add(jcomp7);
add(jcomp8);
add(jcomp9);
// set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds(15, 10, 595, 350);
jcomp2.setBounds(35, 375, 100, 25);
jcomp3.setBounds(190, 375, 100, 25);
jcomp4.setBounds(320, 375, 100, 25);
jcomp5.setBounds(465, 375, 100, 25);
jcomp6.setBounds(35, 450, 100, 25);
jcomp7.setBounds(190, 450, 100, 25);
jcomp8.setBounds(320, 450, 100, 25);
jcomp9.setBounds(465, 450, 100, 25);
}
class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
jcomp1.set(image1);
}
}
}
public static void main (String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
I believe you are trying to get something like this:
public class MyPanel extends JPanel {
private JLabel label;
private JButton[] buttons = new JButton[8];
private ImageIcon[] images = new ImageIcon[8];
public MyPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(2, 4, 15, 10));
for (int i = 0; i < images.length; i++) {
images[i] = new ImageIcon(getClass().getResource(i+1 + ".png"));
buttons[i] = new JButton(String.valueOf(i+1));
buttons[i].setActionCommand(String.valueOf(i+1));
buttons[i].addActionListener(new ButtonClickListener());
buttonPanel.add(buttons[i]);
}
label = new JLabel(images[0]);
setLayout(new BorderLayout());
add(label);
add(buttonPanel, BorderLayout.PAGE_END);
}
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setIcon(images[Integer.parseInt(e.getActionCommand()) - 1]);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible(true);
}
}
Notes:
Don't forget to change the image file name.
You can play with the layout manager to get what you want.
I removed setPreferredSize(new Dimension(624, 537)); because you didn't specify a resize behavior which would make this line meaningless. pack() would take care of the sizes for you.
Set the icon of the button or label. To do this, you need to create an ImageIcon, which has multiple constructors to create from a filename or a loaded image.
jcomp1.setIcon(new ImageIcon(...));

Java swing/awt tabbed pane event

I'm new to java so bear with me:
I want the size of the window/pane/panel to chance once the tab is clicked/changed.
How would I do/impletement this?
I've done it successfully on a button click/event, but how do I do a tab click/event?
Here is my code: (I'm sorry for any bad/bloated/unnessicary code in advance)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//Class shows how to setup up a tabbed window
public class GUI implements ActionListener
{
static JFrame aWindow = new JFrame("Project");
JTabbedPane myTabs = new JTabbedPane();
JPanel loginMainPanel = new JPanel();
JPanel displayMainPanel = new JPanel();
JPanel editMainPanel = new JPanel();
JLabel loginLabel = new JLabel("Username:");
JTextField loginField = new JTextField();
JLabel loginLabel2 = new JLabel("Password:");
JPasswordField loginPass = new JPasswordField();
JButton displayButton = new JButton("Press This Button");
JButton loginButton = new JButton("Login");
JLabel editLabel = new JLabel("Write a story:");
JTextArea editArea = new JTextArea();
public GUI()
{
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize=theKit.getScreenSize();
aWindow.setBounds(wndSize.width/3, wndSize.height/3, 200, 200); //set position, then dimensions
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(1,1);
Container content = aWindow.getContentPane();
content.setLayout(grid);
createLoginPanel();
createDisplayPanel();
createEditPanel();
myTabs.addTab("Login", loginMainPanel);
myTabs.addTab("Display", displayMainPanel);
myTabs.addTab("Edit", editMainPanel);
myTabs.setSelectedIndex(0);
//myTabs.setEnabledAt(1,false);
myTabs.setEnabledAt(2, false);
content.add(myTabs);
aWindow.setVisible(true);
}
public void createLoginPanel()
{
loginMainPanel.setLayout(null);
loginLabel.setBounds(10, 15, 150, 20);
loginMainPanel.add(loginLabel);
loginField.setBounds(10, 35, 150, 20);
loginMainPanel.add(loginField);
loginLabel2.setBounds(10, 60, 150, 20);
loginMainPanel.add(loginLabel2);
loginPass.setBounds(10, 80, 150, 20);
loginMainPanel.add(loginPass);
loginButton.addActionListener(this);
loginButton.setBounds(50, 110, 80, 20);
loginMainPanel.add(loginButton);
}
public void createDisplayPanel()
{
//Toolkit theKit = aWindow.getToolkit();
//Dimension wndSize = theKit.getScreenSize();
//aWindow.setBounds(20, 20, 20, 20); //set position, then dimensions
displayMainPanel.setLayout(null);
displayButton.addActionListener(this);
displayButton.setBounds(10, 80, 150, 20);
displayMainPanel.add(displayButton);
}
public void createEditPanel()
{
editMainPanel.setLayout(null);
editLabel.setBounds(10, 15, 150, 20);
editMainPanel.add(editLabel);
editArea.setBounds(10, 65, 150, 50);
editMainPanel.add(editArea);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//System.out.println("Working...");
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, 300, 300);
}
//Would the event go here?
}
public static void main(String[] args)
{
GUI tw1 = new GUI();
}
}
Thanks very much :)
James,
but how do I do a tab click/event?
Use a ChangeListener.

Categories