I've just begun coding in Java and was wondering how to achieve this. What I want is for the user to be able to input text into a text box, select the font, color and size which will then display in a label at the bottom when the Ok button is clicked. Any help would be appreciated. Thanks.
package textchanger;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class textchanger implements ActionListener {
String[] fontStrings = {"Arial", "Arial Black", "Helvetica", "Impact", "Times New Roman"};
String[] sizeStrings = {"10", "12", "14", "16", "18"};
String[] colorStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] bgStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
JPanel panel;
JLabel labelText, labelFont, labelSize, labelColor, labelBG, labelOutput;
JTextField textField;
JComboBox comboFont, comboSize, comboColor, comboBG;
JButton btnOk, btnCancel;
public JPanel contentPane() { //Creates the GUI
panel = new JPanel();
panel.setLayout(new GridLayout(8, 8, 10, 10));
labelText = new JLabel("Enter Text:");
textField = new JTextField(10);
labelFont = new JLabel("Select font type:");
comboFont = new JComboBox(fontStrings);
comboFont.setSelectedIndex(0);
comboFont.addActionListener(this);
labelSize = new JLabel("Select font size:");
comboSize = new JComboBox(sizeStrings);
comboSize.setSelectedIndex(0);
comboSize.addActionListener(this);
labelColor = new JLabel("Select font color:");
comboColor = new JComboBox(colorStrings);
comboColor.setSelectedIndex(0);
comboColor.addActionListener(this);
labelBG = new JLabel("Select a background color:");
comboBG = new JComboBox(bgStrings);
comboBG.setSelectedIndex(0);
comboBG.addActionListener(this);
btnOk = new JButton("Ok");
btnCancel = new JButton("Cancel");
labelOutput = new JLabel("");
panel.add(labelText);
panel.add(textField);
panel.add(labelFont);
panel.add(comboFont);
panel.add(labelSize);
panel.add(comboSize);
panel.add(labelColor);
panel.add(comboColor);
panel.add(labelBG);
panel.add(comboBG);
panel.add(btnOk);
panel.add(btnCancel);
panel.add(labelOutput);
return panel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fonts, Colors and Sizes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 350);
textchanger txtObj = new textchanger();
frame.setContentPane(txtObj.contentPane());
frame.setVisible(true);
}
}
For clarity and other reasons, I'd avoid making the class implements ActionListener. Just add an anonymous ActionListener to each JComboBox. Something like this
JComboBox comboFont;
JLabel label = new JLabel("label");
String fontString = "ariel";
int fontWeight = Font.PLAIN;
int fontSize = 16;
Font font = new Font(fontString, fontWeight, fontSize);
Color textColor = Color.BLACK
public JPanel contentPane() {
comboFont = new JComboBox(fontStrings);
comboFont.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
fontString = (String)comboFont.getSelectedItem();
font = new Font(fontString, fontWeight, fontSize);
label.setFont(font);
}
});
}
What this will do is dynamically change the font when a new font is selected from the combobox. You should have global values for Font, fontSize and fontWeight so that each different combobox can make use of them and change the font accordingly in the actionPerformed
Also, take a look at this answer from AndrewThompson, showing the actual rendered font style in the JComboBox, with all the fonts obtained from the system fonts. Here's a glimpse. Don't forget to up-vote the answer in the link!
Give this a try. I revamped your code
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class textchanger {
//String[] fontStrings = {"Arial", "Arial Black", "Helvetica", "Impact", "Times New Roman"};
Integer[] fontSizes = {10, 12, 14, 16, 18, 20, 22, 24};
String[] colorStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] bgStrings = {"Red", "Blue", "Green", "Yellow", "Orange"};
String[] fontStyle = {"BOLD", "Italic", "Plain"};
JPanel panel;
JLabel labelText, labelFont, labelSize, labelColor, labelBG, labelOutput;
JTextField textField;
JComboBox comboFont, comboSize, comboColor, comboBG;
JButton btnOk, btnCancel;
String fontString;
int fontWeight = Font.PLAIN;
int fontSize;
Font font = new Font(fontString, Font.PLAIN, fontSize);
Color textColor;
Color bgColor;
static String text = "Text";
static JLabel textLabel = new JLabel(text);
JPanel textLabelPanel = new JPanel(new GridBagLayout());
public JPanel contentPane() { //Creates the GUI
panel = new JPanel();
panel.setLayout(new GridLayout(7, 8, 10, 10));
textLabelPanel.setPreferredSize(new Dimension(500, 50));
labelText = new JLabel("Enter Text:");
textField = new JTextField(10);
textField.setText(text);
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
String newText = textField.getText();
textLabel.setText(newText);
}
#Override
public void removeUpdate(DocumentEvent e) {
String newText = textField.getText();
textLabel.setText(newText);
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
labelFont = new JLabel("Select font type:");
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
comboFont = new JComboBox(fonts);
fontString = (String) comboFont.getItemAt(0);
comboFont.setSelectedIndex(0);
comboFont.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontString = (String) comboFont.getSelectedItem();
font = new Font(fontString, fontWeight, fontSize);
textLabel.setFont(font);
}
});
labelSize = new JLabel("Select font size:");
comboSize = new JComboBox(fontSizes);
comboSize.setSelectedIndex(0);
fontSize = (Integer) comboSize.getItemAt(0);
comboSize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fontSize = (Integer) comboSize.getSelectedItem();
font = new Font(fontString, fontWeight, fontSize);
textLabel.setFont(font);
}
});
labelColor = new JLabel("Select font color:");
comboColor = new JComboBox(colorStrings);
comboColor.setSelectedIndex(0);
textColor = Color.RED;
textLabel.setForeground(textColor);
comboColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String colorString = (String) comboColor.getSelectedItem();
switch (colorString) {
case "Red":
textColor = Color.RED;
break;
case "Blue":
textColor = Color.BLUE;
break;
case "Green":
textColor = Color.GREEN;
break;
case "Yellow":
textColor = Color.YELLOW;
break;
case "Orange":
textColor = Color.ORANGE;
break;
default:
textColor = Color.RED;
}
textLabel.setForeground(textColor);
}
});
labelBG = new JLabel("Select a background color:");
comboBG = new JComboBox(bgStrings);
comboBG.setSelectedIndex(1);
bgColor = Color.BLUE;
textLabelPanel.setBackground(bgColor);
comboBG.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String bgColorString = (String) comboBG.getSelectedItem();
switch (bgColorString) {
case "Red":
bgColor = Color.RED;
break;
case "Blue":
bgColor = Color.BLUE;
break;
case "Green":
bgColor = Color.GREEN;
break;
case "Yellow":
bgColor = Color.YELLOW;
break;
case "Orange":
bgColor = Color.ORANGE;
break;
default:
bgColor = Color.RED;
}
textLabelPanel.setBackground(bgColor);
}
});
btnOk = new JButton("Ok");
btnCancel = new JButton("Cancel");
labelOutput = new JLabel("");
panel.add(labelText);
panel.add(textField);
panel.add(labelFont);
panel.add(comboFont);
panel.add(labelSize);
panel.add(comboSize);
panel.add(labelColor);
panel.add(comboColor);
panel.add(labelBG);
panel.add(comboBG);
panel.add(btnOk);
panel.add(btnCancel);
panel.add(labelOutput);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(panel);
textLabelPanel.add(textLabel);
mainPanel.add(textLabelPanel, BorderLayout.SOUTH);
return mainPanel;
}
class FontCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
Font font = new Font((String) value, Font.PLAIN, 20);
label.setFont(font);
return label;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Fonts, Colors and Sizes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 350);
textchanger txtObj = new textchanger();
frame.setContentPane(txtObj.contentPane());
frame.setVisible(true);
}
});
}
}
Related
I want to create a Text Editor in Java. Here is what I've written so far:
package com.thundercrust.applications;
import java.awt.BorderLayout;
public class TextEditor implements ActionListener{
private static String[] fontOptions = {"Serif", "Agency FB", "Arial", "Calibri", "Cambrian", "Century Gothic", "Comic Sans MS", "Courier New", "Forte", "Garamond", "Monospaced", "Segoe UI", "Times New Roman", "Trebuchet MS", "Serif"};
private static String[] sizeOptions = {"8", "10", "12", "14", "16", "18", "20", "22", "24", "26", "28"};
ImageIcon newIcon = new ImageIcon("res/NewIcon.png");
ImageIcon saveIcon = new ImageIcon("res/SaveIcon.png");
ImageIcon openIcon = new ImageIcon("res/OpenIcon.png");
ImageIcon fontIcon = new ImageIcon("res/FontIcon.png");
ImageIcon changeFontIcon = new ImageIcon("res/ChangeFontIcon.png");
JButton New = new JButton(newIcon);
JButton Save = new JButton(saveIcon);
JButton Open = new JButton(openIcon);
JButton changeFont = new JButton(changeFontIcon);
JLabel fontLabel = new JLabel(fontIcon);
JLabel fontLabelText = new JLabel("Font: ");
JLabel fontSizeLabel = new JLabel("Size: ");
JComboBox <String> fontName = new JComboBox<>(fontOptions);
JComboBox <String> fontSize = new JComboBox<>(sizeOptions);
JToolBar tool = new JToolBar();
JTextArea texty = new JTextArea();
JScrollPane scroll = new JScrollPane(texty);
private static final int WIDTH = 1366;
private static final int HEIGHT = WIDTH / 16 * 9;
private static String name = "Text Editor";
private static JFrame frame = new JFrame();
public void Display() {
frame.setTitle(name);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
New.addActionListener(this);
New.setToolTipText("Creates a new File");
Save.addActionListener(this);
Save.setToolTipText("Saves the current File");
Open.addActionListener(this);
Open.setToolTipText("Opens a file");
changeFont.addActionListener(this);
changeFont.setToolTipText("Change the Font");
fontLabel.setToolTipText("Font");
fontLabelText.setToolTipText("Set the kind of Font");
fontSizeLabel.setToolTipText("Set the size of the Font");
tool.add(New);
tool.addSeparator();
tool.add(Save);
tool.addSeparator();
tool.add(Open);
tool.addSeparator();
tool.addSeparator();
tool.addSeparator();
tool.add(fontLabel);
tool.addSeparator();
tool.add(fontLabelText);
tool.add(fontName);
tool.addSeparator();
tool.add(fontSizeLabel);
tool.add(fontSize);
tool.addSeparator();
tool.add(changeFont);
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(tool, "North");
pane.add(scroll, "Center");
frame.setContentPane(pane);
}
public static void main(String args[]) {
TextEditor editor = new TextEditor();
editor.Display();
}
public void actionPerformed(ActionEvent evt) {
String fontNameSet;
String fontSizeSetTemp;
int fontSizeSet;
Object source = evt.getSource();
if(source == New) {
texty.setText("");
}
else if(source == changeFont) {
fontNameSet = (String) fontName.getSelectedItem();
fontSizeSetTemp = (String) fontSize.getSelectedItem();
fontSizeSet = Integer.parseInt(fontSizeSetTemp);
System.out.println(fontNameSet + fontSizeSet);
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
}
}
}
My problem is with setting fonts for the JTextArea. When I click the changeFont button on my actual program, nothing happens. What do I do?
new Font(fontNameSet, fontSizeSet, Font.PLAIN)
This has the arguments in the wrong order. It should be:
new Font(fontNameSet, Font.PLAIN, fontSizeSet)
Also, as mentioned in a comment:
scroll.setFont(new Font(fontNameSet, fontSizeSet, Font.PLAIN));
Should be:
texty.setFont(new Font(fontNameSet, Font.PLAIN, fontSizeSet));
This question already has answers here:
Java null layout results in a blank screen
(2 answers)
Closed 8 years ago.
Program is Compiling and running but it is not displaying anything on the frame just a blank screen.
i am making main menu for my game using cardLayout, i have made different classes for every panel and then added them in cardlayout in Frame
Kindly some one please pinpoint the mistake i am doing i cant find it..
thankyou
enter code here
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class MainMenu extends JFrame implements ActionListener{
static CardLayout cl2;
static JPanel cardPanel;
Name p1;
MainM p2;
Robot p3;
High p4;
Inst p5;
gamepanel gp;
public static int height;
public static int width;
public static void main(String args[]){
MainMenu cl = new MainMenu();
cl.What();
}
public void What() {
// get the screen size as a java dimension
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
setTitle("EROBOT");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// get height, and width
height = screenSize.height ;
width = screenSize.width ;
// set the jframe height and width
setSize(new Dimension(width, height));
cardPanel = new JPanel();
p1= new Name();
p2= new MainM();
p3= new Robot();
p4= new High();
p5= new Inst();
gp= new gamepanel();
cl2 = new CardLayout();
cardPanel.setLayout(cl2);
cardPanel.add(p1, "name");
cardPanel.add(p2, "menu");
cardPanel.add(p3, "robo");
cardPanel.add(p4, "inst");
cardPanel.add(p5, "high");
cardPanel.add(gp, "start");
getContentPane().add(cardPanel);
//name
Name.done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
// Main
MainM.newg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "start" );
}
});
MainM.high.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "high" );
}
});
MainM.robo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "robo" );
}
});
MainM.inst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "inst" );
}
});
/////////////////////
//Robot
Robot.go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "start" );
}
});
Robot.back1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
//high score
High.back2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
//how to play
Inst.back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
}
public void actionPerformed(ActionEvent e){}
}
class Name extends JPanel{
JLabel enter;
static JButton done;
JTextField name;
JPanel side;
JPanel up;
JLabel title;
Name(){
Color h3= new Color(255,229,204);
side= new JPanel();
up= new JPanel();
setLayout(null);
MainMenu mm= new MainMenu();
setBackground(h3);
title = new JLabel("E-ROBOT");
title.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title.setBounds(520, 100, 300, 50);
enter= new JLabel("ENTER YOUR NAME HERE");
enter.setFont(new Font("Ravie", Font.PLAIN, 20));
enter.setForeground(Color.orange);
enter.setBounds(370, 200, 350, 50);
name = new JTextField();
name.setBounds(390, 250, 150, 25);
done= new JButton("DONE");
done.setFont(new Font("Ravie", Font.PLAIN, 20));
done.setForeground(Color.orange);
done.setBackground(Color.YELLOW);
done.setOpaque(false);
done.setBorder(null);
done.setBounds(400, 280, 150, 30);
side.setBounds(0,40,mm.width,60);
up.setBounds(40,0,40,mm.height);
side.setBackground(Color.ORANGE);
up.setBackground(Color.ORANGE);
side.add(title);
add(enter);
add(name);
add(done);
add(side);
add(up);
}
}
class MainM extends JPanel{
JPanel l1;
JPanel l2;
JPanel l3;
JPanel l4;
JPanel contain;
JPanel side1;
JPanel up1;
static JButton newg;
static JButton high;
static JButton robo;
static JButton inst;
JLabel title;
MainM(){
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
setBackground(h3);
l1= new JPanel();
l2= new JPanel();
l3= new JPanel();
l4= new JPanel();
contain= new JPanel();
side1= new JPanel();
up1= new JPanel();
title = new JLabel("E-ROBOT");
title.setFont(new Font("Ravie", Font.PLAIN, 40));
title.setForeground(Color.WHITE);
title.setBounds(520, 100, 300, 50);
//custom colors
Color b1= new Color(99,230,199);
Color h= new Color(132,234,23);
Color h1= new Color(45,99,120);
Color h2= new Color(0,0,101);
Color h4= new Color(154,0,0);
l1.setBounds(480,200,10,525);
l1.setBackground(h4);
l2.setBounds(465,210,565,10);
l2.setBackground(h4);
l3.setBounds(1000,200,10,525);
l3.setBackground(h4);
l4.setBounds(465,690,565,10);
l4.setBackground(h4);
// settings style amd font of buttons
newg = new JButton("New Game");
newg.setFont(new Font("Ravie", Font.PLAIN, 25));
newg.setBackground(Color.YELLOW);
newg.setOpaque(false);
newg.setBorder(null);
newg.setForeground(h2);
high = new JButton("High Scores");
robo= new JButton("Select your Robot");
inst = new JButton("How to Play");
high.setFont(new Font("Ravie", Font.PLAIN, 25));
high.setBackground(Color.YELLOW);
high.setOpaque(false);
high.setBorder(null);
high.setForeground(h1);
robo.setFont(new Font("Ravie", Font.PLAIN, 25));
robo.setBackground(Color.YELLOW);
robo.setOpaque(false);
robo.setBorder(null);
robo.setForeground(h);
inst.setFont(new Font("Ravie", Font.PLAIN, 25));
inst.setBackground(Color.YELLOW);
inst.setOpaque(false);
inst.setBorder(null);
inst.setForeground(Color.MAGENTA);
contain.setBounds(490,220,490,460);
contain.setLayout(new GridLayout(4,1));
side1.setBounds(0,40,mm.width,60);
up1.setBounds(40,0,40,mm.height);
side1.setBackground(h4);
up1.setBackground(h4);
//adding all the JComponents to the screen
side1.add(title);
contain.add(newg);
contain.add(high);
contain.add(robo);
contain.add(inst);
add(l1);
add(l2);
add(l3);
add(l4);
add(side1);
add(up1);
add(contain);
}
}
class Robot extends JPanel{
ImageIcon a;
ImageIcon b;
ImageIcon c;
JPanel side2;
JPanel up2;
static JButton r1;
static JButton r2;
static JButton r3;
static JButton back1;
static JButton go;
JLabel title1;
Robot(){
Color h= new Color(132,234,23);
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
Color h4= new Color(154,0,0);
side2= new JPanel();
up2= new JPanel();
r1= new JButton();
r2= new JButton();
r3= new JButton();
back1= new JButton("Back");
go= new JButton("LEt's go");
a = new ImageIcon(getClass().getResource("a.gif"));
b = new ImageIcon(getClass().getResource("b.gif"));
c = new ImageIcon(getClass().getResource("c.gif"));
//adding the ImageIcons to the JButtons
r1 = new JButton(a);
r1.setBounds(120,120,300,300);
r1.setBackground(Color.YELLOW);
r1.setOpaque(false);
r1.setBorder(null);
r2 = new JButton(b);
r2.setBounds(460,120,300,300);
r2.setBackground(Color.YELLOW);
r2.setOpaque(false);
r2.setBorder(null);
r3 = new JButton(c);
r3.setBounds(890,120,300,300);
r3.setBackground(Color.YELLOW);
r3.setOpaque(false);
r3.setBorder(null);
back1 = new JButton("Let's Go!");
back1.setBounds(520, 500, 170, 60);
back1.setFont(new Font("Ravie", Font.PLAIN, 25));
back1.setBackground(Color.YELLOW);
back1.setOpaque(false);
back1.setBorder(null);
setLayout(null);
title1 = new JLabel("E-ROBOT");
title1.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
// title1.setBounds(520, 100, 300, 50);
side2.setBounds(0,40,mm.width,60);
up2.setBounds(40,0,40,mm.height);
side2.setBackground(h);
up2.setBackground(h);
side2.add(title1);
add(side2);
add(up2);
add(r1);
add(r2);
add(r3);
add(back1);
add(go);
}
}
class High extends JPanel{
JLabel title3;
static JButton back2;
JPanel side4;
JPanel up4;
High()
{
Color h= new Color(132,234,23);
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
side4 = new JPanel();
up4= new JPanel();
Color h1= new Color(45,99,120);
setLayout(null);
title3 = new JLabel("E-ROBOT");
title3.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title3.setBounds(520, 100, 300, 50);
back2= new JButton("Back");
back2.setBounds(500,500,120,30);
back2.setFont(new Font("Ravie", Font.PLAIN, 25));
back2.setBackground(Color.YELLOW);
back2.setOpaque(false);
back2.setBorder(null);
side4.setBounds(0,40,mm.width,60);
up4.setBounds(40,0,40,mm.height);
side4.setBackground(h1);
up4.setBackground(h1);
side4.add(title3);
add(side4);
add(up4);
add(back2);
}
}
class Inst extends JPanel{
JLabel jl1;
JLabel jl2;
JLabel jl3;
JLabel jl4;
JLabel jl5;
JLabel title2;
JPanel side3;
JPanel up3;
static JButton back;
JPanel contain2;
Inst(){
MainMenu mm= new MainMenu();
contain2= new JPanel();
side3= new JPanel();
up3= new JPanel();
Color h= new Color(132,234,23);
Color h3= new Color(255,229,204);
jl1= new JLabel("Welcome aboard\n !");
jl2 = new JLabel("So the game is simple.\n");
jl3 = new JLabel("You have to catch even number only\n.");
jl4 = new JLabel("A life ends if you catch an odd number.\n");
jl5 = new JLabel("Oh and also the game gets more difficult when your lives end!\n");
jl1.setFont(new Font("Ravie", Font.PLAIN, 20));
jl2.setFont(new Font("Ravie", Font.PLAIN, 20));
jl3.setFont(new Font("Ravie", Font.PLAIN, 20));
jl4.setFont(new Font("Ravie", Font.PLAIN, 20));
jl5.setFont(new Font("Ravie", Font.PLAIN, 20));
jl1.setForeground(Color.magenta);
jl2.setForeground(Color.magenta);
jl3.setForeground(Color.magenta);
jl4.setForeground(Color.magenta);
jl5.setForeground(Color.magenta);
title2 = new JLabel("E-ROBOT");
title2.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title2.setBounds(520, 100, 300, 50);
back = new JButton("Back");
back.setFont(new Font("Ravie", Font.PLAIN, 15));
back.setBackground(Color.YELLOW);
back.setOpaque(false);
back.setBorder(null);
setLayout(null);
contain2.setBounds(80,200,800,400);
contain2.setBackground(h3);
side3.setBounds(0,40,mm.width,60);
up3.setBounds(40,0,40,mm.height);
side3.setBackground(Color.MAGENTA);
up3.setBackground(Color.MAGENTA);
side3.add(title2);
contain2.add(jl1);
contain2.add(jl2);
contain2.add(jl3);
contain2.add(jl4);
contain2.add(jl5);
contain2.add(back);
add(contain2);
add(side3);
add(up3);
}
}
I'm not sure whether it helps (sorry but your code is too large and bad formatted, so I cannot understand it), but you can try to revalidate and repaint the root pane or content pane of JFrame each time when you update your GUI.
Something like this
public static void updateRootPane(JComponent aComponent) {
Window w = SwingUtilities.windowForComponent(aComponent);
if (w instanceof JFrame) {
((JFrame) w).getRootPane().revalidate();
((JFrame) w).getRootPane().repaint();
} else if (w instanceof JDialog) {
((JDialog) w).getRootPane().revalidate();
((JDialog) w).getRootPane().repaint();
}
}
I have created a JFrame where the user can edit text in a JTextArea. There is a JComboBox to change font type, a JComboBox to change font size, and 2 JCheckBoxes to make the text Bold and Italic. I have finished the JCheckBoxes, but I cannot figure out how to allow change font and font size by using the JComoboBoxes. Any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SetFontModified extends JFrame
{
private JPanel p1, p2;
private JLabel jlblFontName, jlblFontSize;
private JComboBox jcbFonts, jcbSizes;
private JTextArea jtxtWelcome;
private JCheckBox jckbBold, jckbItalic;
public SetFontModified()
{
p1 = new JPanel();
jlblFontName = new JLabel("Font Name");
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = e.getAvailableFontFamilyNames();
jcbFonts = new JComboBox(fontNames);
jlblFontSize = new JLabel("Font Size");// add 2nd JLabel
jcbSizes = new JComboBox(); // create 2nd JComboBox
for(int i = 1; i < 101; i ++) // populate JComboBox with array of font sizes 1-100
{
jcbSizes.addItem(i);
}
p1.add(jlblFontName); // add all 4 components to p1
p1.add(jcbFonts);
p1.add(jlblFontSize);
p1.add(jcbSizes);
jtxtWelcome = new JTextArea("Welcome to Java", 3, 20);// add a JTextArea
add(jtxtWelcome);
p2 = new JPanel(); // create p2 & add JCheckBoxes
p2.add(jckbBold = new JCheckBox("Bold"));
jckbBold.setMnemonic('B');
p2.add(jckbItalic = new JCheckBox("Italic"));
jckbItalic.setMnemonic('I');
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
ListenerClass listener = new ListenerClass();
jcbFonts.addActionListener(listener);
jcbSizes.addActionListener(listener);
jckbBold.addActionListener(listener);
jckbItalic.addActionListener(listener);
}
public static void main(String[] args)
{
SetFontModified frame = new SetFontModified();
frame.setTitle("Set Font Details");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jcbSizes.getFontSize();
Font plainFont = new Font("serif", Font.PLAIN, size);
Font boldFont = new Font("serif", Font.BOLD, 14);
Font italicFont = new Font("serif", Font.ITALIC, 14);
Font boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);
if (jckbBold.isSelected() && jckbItalic.isSelected())
jtxtWelcome.setFont(boldItalicFont);
else if (jckbBold.isSelected())
jtxtWelcome.setFont(boldFont);
else if (jckbItalic.isSelected())
jtxtWelcome.setFont(italicFont);
else jtxtWelcome.setFont(plainFont);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame
{
private JPanel p1, p2;
private JLabel jlblFontName, jlblFontSize;
private JComboBox jcbFonts, jcbSizes;
private JTextArea jtxtWelcome;
private JCheckBox jckbBold, jckbItalic;
public Test()
{
p1 = new JPanel();
jlblFontName = new JLabel("Font Name");
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = e.getAvailableFontFamilyNames();
jcbFonts = new JComboBox(fontNames);
jlblFontSize = new JLabel("Font Size"); // add 2nd JLabel
jcbSizes = new JComboBox(); // create 2nd JComboBox
for(int i = 1; i < 101; i ++) // populate JComboBox with array of font sizes 1-100
{
jcbSizes.addItem(i);
}
p1.add(jlblFontName); // add all 4 components to p1
p1.add(jcbFonts);
p1.add(jlblFontSize);
p1.add(jcbSizes);
jtxtWelcome = new JTextArea("Welcome to Java", 3, 20); // add a JTextArea
add(jtxtWelcome);
p2 = new JPanel(); // create p2 & add JCheckBoxes
p2.add(jckbBold = new JCheckBox("Bold"));
jckbBold.setMnemonic('B');
p2.add(jckbItalic = new JCheckBox("Italic"));
jckbItalic.setMnemonic('I');
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
ListenerClass listener = new ListenerClass();
jcbFonts.addActionListener(listener);
jcbSizes.addActionListener(listener);
jckbBold.addActionListener(listener);
jckbItalic.addActionListener(listener);
}
public static void main(String[] args)
{
Test frame = new Test();
frame.setTitle("Set Font Details");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//jcbSizes.getFontSize();
Font plainFont = new Font("serif", Font.PLAIN, Integer.parseInt(jcbSizes.getSelectedItem().toString()));
Font boldFont = new Font("serif", Font.BOLD, 14);
Font italicFont = new Font("serif", Font.ITALIC, 14);
Font boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);
if (jckbBold.isSelected() && jckbItalic.isSelected())
jtxtWelcome.setFont(boldItalicFont);
else if (jckbBold.isSelected())
jtxtWelcome.setFont(boldFont);
else if (jckbItalic.isSelected())
jtxtWelcome.setFont(italicFont);
else jtxtWelcome.setFont(plainFont);
}
}
}
You need the correct method for jcbSizes:
int size = (Integer) jcbSizes.getSelectedItem();
The compiler is complaining about an undefined variable size. You can add this declaration to your ActionListener:
int size = (Integer)jcbSizes.getSelectedItem();
but I cannot figure out how to allow change font and font size by
using the JComoboBoxes.
For this to happen you have to change your else block like follows.
else {
// jcbFonts.getSelectedItem().toString()
// gets font string selected in font combobox
// -------------------------------------
// jcbSizes.getSelectedIndex())
// get font size selected in size combobox
jtxtWelcome.setFont(new Font(jcbFonts.getSelectedItem()
.toString(), Font.PLAIN, jcbSizes.getSelectedIndex()));
System.out.println("Font Name: " + jcbFonts.getSelectedItem()
+ " Font Size:" + jcbSizes.getSelectedIndex());
}
Class Font API
I am using Metal L&F. I want to make a JComboBox, that has only 1 pixel border. This not a problem, as long as the cb is editable. This corresponds to the first cb in the picture named "Editable".
cb.setEditable(true);
((JTextComponent) (cb.getEditor().getEditorComponent())).setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, COLOR));
But when I do cb.setEditable(false), an additional border occurs inside the box (changed to red in the picture "Dropdown", you see the original color in the picture named "Fixed"). Although I tried to set the border and I also tried to use my own CellRenderer, the border still gets painted. It seems to me, that the unwanted border does not come from the CellRenderer. When I try to manipulate the border from the cb itself (see comment //), it only adds/removes an additional outer border. The editorComponent also seems not to be responsible to me.
cb.setRenderer(new CbCellRenderer());
//cb.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, COLOR));
//cb.setBorder(BorderFactory.createEmptyBorder());
class CbCellRenderer implements ListCellRenderer {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
renderer.setBorder(BorderFactory.createEmptyBorder());
return renderer;
}
}
I also tried out some UI variables like the ones below without taking affect on this border.
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
UIManager.put("ComboBox.selectionForeground", Color.green);
UIManager.put("ComboBox.disabledBackground", Color.green);
...
Image: http://upload.mtmayr.com/dropdown_frame.png (link broken)
Complete code for testing:
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboPopup;
public class ComboTest {
private Vector<String> listSomeString = new Vector<String>();
private JComboBox editableComboBox = new JComboBox(listSomeString);
private JComboBox nonEditableComboBox = new JComboBox(listSomeString);
private JFrame frame;
public final static Color COLOR_BORDER = new Color(122, 138, 153);
public ComboTest() {
listSomeString.add("row 1");
listSomeString.add("row 2");
listSomeString.add("row 3");
listSomeString.add("row 4");
editableComboBox.setEditable(true);
editableComboBox.setBackground(Color.white);
Object child = editableComboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup) child;
JList list = popup.getList();
list.setBackground(Color.white);
list.setSelectionBackground(Color.red);
JTextField tf = ((JTextField) editableComboBox.getEditor().getEditorComponent());
tf.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, COLOR_BORDER));
nonEditableComboBox.setEditable(false);
nonEditableComboBox.setBorder(BorderFactory.createEmptyBorder());
nonEditableComboBox.setBackground(Color.white);
Object childNonEditable = nonEditableComboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popupNonEditable = (BasicComboPopup) childNonEditable;
JList listNonEditable = popupNonEditable.getList();
listNonEditable.setBackground(Color.white);
listNonEditable.setSelectionBackground(Color.red);
frame = new JFrame();
frame.setLayout(new GridLayout(0, 1, 10, 10));
frame.add(editableComboBox);
frame.add(nonEditableComboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboTest ct = new ComboTest();
}
});
}
}
How about override MetalComboBoxUI#paintCurrentValueBackground(...)
using JDK 1.7.0_17, Windows 7
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
public class ComboBoxUIDemo {
private static Color BORDER = Color.GRAY;
public JComponent makeUI() {
//UIManager.put("ComboBox.foreground", Color.WHITE);
//UIManager.put("ComboBox.background", Color.BLACK);
//UIManager.put("ComboBox.selectionForeground", Color.CYAN);
//UIManager.put("ComboBox.selectionBackground", Color.BLACK);
//UIManager.put("ComboBox.buttonDarkShadow", Color.WHITE);
//UIManager.put("ComboBox.buttonBackground", Color.GRAY);
//UIManager.put("ComboBox.buttonHighlight", Color.WHITE);
//UIManager.put("ComboBox.buttonShadow", Color.WHITE);
//UIManager.put("ComboBox.editorBorder", BorderFactory.createLineBorder(Color.RED));
Box box = Box.createVerticalBox();
UIManager.put("ComboBox.border", BorderFactory.createEmptyBorder());
for(int i=0; i<2; i++) { // Defalut
JComboBox<String> cb = new JComboBox<>(makeModel());
if(i%2==0) setEditable(cb);
setPopupBorder(cb);
box.add(cb);
box.add(Box.createVerticalStrut(10));
}
{
// Override MetalComboBoxUI#paintCurrentValueBackground(...)
JComboBox<String> cb = new JComboBox<>(makeModel());
cb.setUI(new MetalComboBoxUI() {
#Override public void paintCurrentValueBackground(
Graphics g, Rectangle bounds, boolean hasFocus) {
//if (MetalLookAndFeel.usingOcean()) {
if(MetalLookAndFeel.getCurrentTheme() instanceof OceanTheme) {
g.setColor(MetalLookAndFeel.getControlDarkShadow());
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height - 1);
//COMMENTOUT>>>
//g.setColor(MetalLookAndFeel.getControlShadow());
//g.drawRect(bounds.x + 1, bounds.y + 1, bounds.width - 2,
// bounds.height - 3);
//<<<COMMENTOUT
if (hasFocus && !isPopupVisible(comboBox) && arrowButton != null) {
g.setColor(listBox.getSelectionBackground());
Insets buttonInsets = arrowButton.getInsets();
if (buttonInsets.top > 2) {
g.fillRect(bounds.x + 2, bounds.y + 2, bounds.width - 3,
buttonInsets.top - 2);
}
if (buttonInsets.bottom > 2) {
g.fillRect(bounds.x + 2, bounds.y + bounds.height -
buttonInsets.bottom, bounds.width - 3,
buttonInsets.bottom - 2);
}
}
} else if (g == null || bounds == null) {
throw new NullPointerException(
"Must supply a non-null Graphics and Rectangle");
}
}
});
setPopupBorder(cb);
box.add(cb);
box.add(Box.createVerticalStrut(10));
}
UIManager.put("ComboBox.border", BorderFactory.createLineBorder(BORDER));
for(int i=0; i<2; i++) { // BasicComboBoxUI
JComboBox<String> cb = new JComboBox<>(makeModel());
if(i%2==0) setEditable(cb);
cb.setUI(new BasicComboBoxUI());
setPopupBorder(cb);
box.add(cb);
box.add(Box.createVerticalStrut(10));
}
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
p.add(box, BorderLayout.NORTH);
return p;
}
private static void setEditable(JComboBox cb) {
cb.setEditable(true);
ComboBoxEditor editor = cb.getEditor();
Component c = editor.getEditorComponent();
if(c instanceof JTextField) {
JTextField tf = (JTextField)c;
tf.setBorder(BorderFactory.createMatteBorder(1,1,1,0,BORDER));
}
}
private static void setPopupBorder(JComboBox cb) {
Object o = cb.getAccessibleContext().getAccessibleChild(0);
JComponent c = (JComponent)o;
c.setBorder(BorderFactory.createMatteBorder(0,1,1,1,BORDER));
}
private static DefaultComboBoxModel<String> makeModel() {
DefaultComboBoxModel<String> m = new DefaultComboBoxModel<>();
m.addElement("1234");
m.addElement("5555555555555555555555");
m.addElement("6789000000000");
return m;
}
public static void main(String[] args) {
// OceanTheme theme = new OceanTheme() {
// #Override protected ColorUIResource getSecondary2() {
// return new ColorUIResource(Color.RED);
// }
// };
// MetalLookAndFeel.setCurrentTheme(theme);
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ComboBoxUIDemo().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
not able to ...., every have got the same Borders, there must be another issue, 1st and 2nd. are editable JComboBoxes
for better help sooner post an SSCCE, short, runnable, compilable, just about two JComboBoxes, Native OS, compiled in JDK, runned in JRE
WinXP Java6
Win7 Java7
Win7 Java6
Win8 Java6
Win8 Java7
from code
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalComboBoxButton;
public class MyComboBox {
private Vector<String> listSomeString = new Vector<String>();
private JComboBox someComboBox = new JComboBox(listSomeString);
private JComboBox editableComboBox = new JComboBox(listSomeString);
private JComboBox non_EditableComboBox = new JComboBox(listSomeString);
private JFrame frame;
public MyComboBox() {
listSomeString.add("-");
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
//
someComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
someComboBox.setFont(new Font("Serif", Font.BOLD, 16));
someComboBox.setEditable(true);
someComboBox.getEditor().getEditorComponent().setBackground(Color.YELLOW);
((JTextField) someComboBox.getEditor().getEditorComponent()).setBackground(Color.YELLOW);
//
editableComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
editableComboBox.setFont(new Font("Serif", Font.BOLD, 16));
editableComboBox.setEditable(true);
JTextField text = ((JTextField) editableComboBox.getEditor().getEditorComponent());
text.setBackground(Color.YELLOW);
JComboBox coloredArrowsCombo = editableComboBox;
Component[] comp = coloredArrowsCombo.getComponents();
for (int i = 0; i < comp.length; i++) {
if (comp[i] instanceof MetalComboBoxButton) {
MetalComboBoxButton coloredArrowsButton = (MetalComboBoxButton) comp[i];
coloredArrowsButton.setBackground(null);
break;
}
}
//
non_EditableComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
non_EditableComboBox.setFont(new Font("Serif", Font.BOLD, 16));
//
frame = new JFrame();
frame.setLayout(new GridLayout(0, 1, 10, 10));
frame.add(someComboBox);
frame.add(editableComboBox);
frame.add(non_EditableComboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
UIManager.put("ComboBox.background", new ColorUIResource(Color.yellow));
UIManager.put("JTextField.background", new ColorUIResource(Color.yellow));
UIManager.put("ComboBox.selectionBackground", new ColorUIResource(Color.magenta));
UIManager.put("ComboBox.selectionForeground", new ColorUIResource(Color.blue));
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyComboBox aCTF = new MyComboBox();
}
});
}
}
I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}