How to put JComboBox into an Applet - java

I have this code below. How do I make this JComboBOx run in an Applet? I'm trying to create an applet that allows the user to select a font and type in that font in a JTextArea. I have been searching for answers and made little progress. The error java.lang.reflect.InvocationTargetException keeps popping up. If you need more specifics please just comment.
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Font_Chooser extends JApplet {
JLabel jlbPicture;
public Font_Chooser(){
// Create the combo box, and set first item as Default
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] names = ge.getAvailableFontFamilyNames();
final JComboBox comboTypesList = new JComboBox(names);
comboTypesList.setSelectedIndex(0);
comboTypesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcmbType = (JComboBox) e.getSource();
String cmbType = (String) jcmbType.getSelectedItem();
jlbPicture.setIcon(new ImageIcon(""
+ cmbType.trim().toLowerCase() + ".jpg"));
System.out.println(comboTypesList.getSelectedItem());
//Font myFont = new Font((String)comboTypesList.getSelectedItem(), Font.BOLD, 12);
}
});
// Set up the picture
jlbPicture = new JLabel(new ImageIcon(""
+ names[comboTypesList.getSelectedIndex()] + ".jpg"));
jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));
// Layout the demo
setLayout(new BorderLayout());
add(comboTypesList, BorderLayout.NORTH);
add(jlbPicture, BorderLayout.SOUTH);
}
public static void main(String s[]) {
JFrame frame = new JFrame("JComboBox Usage Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new Font_Chooser());
frame.pack();
frame.setVisible(true);
}
}

Related

actionPerformed is not being called when buttons are pressed pn my dialog box

When I click the buttons I added for ok and cancel, actionPerformed does not get called
code:
void testServerFlags()
{
dlgEmpty mdlgCreateBot = new dlgEmpty(null);
mdlgCreateBot.show();
ted=0;
}
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import Indicator.cGenIndicator;
import Indicator.cIndicatorUtil;
import MyLib.cLib;
public class dlgEmpty extends JDialog implements ActionListener
{
Box parPan, topPan, butPan,centerPan;;
public dlgEmpty(JFrame parent)
{
super(parent,"Indicators", true);
Container content = getContentPane();
content.setLayout(new BorderLayout());
butPan = Box.createHorizontalBox();
JButton okBut = new JButton("OK");
okBut.setActionCommand("ok");
butPan.add(okBut, BorderLayout.SOUTH);
JButton CancelBut = new JButton("Cancel");
CancelBut.setActionCommand("Cancel");
butPan.add(CancelBut, BorderLayout.SOUTH);
content.add(butPan, BorderLayout.SOUTH);
centerPan = Box.createVerticalBox();
content.add(centerPan, BorderLayout.CENTER);
pack();
show();
}
boolean isOk=false;
public void actionPerformed(ActionEvent e)
{
if ("OK".equals(e.getActionCommand()))
isOk=true;
setVisible(false);
}
}
You are setting the action command to:
okBut.setActionCommand("ok");
But are checking for:
if ("OK".equals(e.getActionCommand()))
This won't match, because the case is different.
setActionCommand only sets the message in the ActionEvent. What you need is addActionListener. I have updated your code.
But the other thing you should know is that there is no need for this. Instead use JOptionPane.showConfirmDialog with a JComponent as the message parameter: It does all the button handling and modal in-line waiting automatically
public dlgEmpty(JFrame parent)
{
super(parent,"Indicators", true);
Container content = getContentPane();
content.setLayout(new BorderLayout());
butPan = Box.createHorizontalBox();
JButton okBut = new JButton("OK");
okBut.setActionCommand("ok");
okBut.addActionListener(this); // added this line
butPan.add(okBut, BorderLayout.SOUTH);
JButton CancelBut = new JButton("Cancel");
CancelBut.setActionCommand("Cancel");
CancelBut.addActionListener(this);
butPan.add(CancelBut, BorderLayout.SOUTH); //added this line
content.add(butPan, BorderLayout.SOUTH);
centerPan = Box.createVerticalBox();
content.add(centerPan, BorderLayout.CENTER);
pack();
show();
}
boolean isOk=false;
public void actionPerformed(ActionEvent e)
{
if ("OK".equals(e.getActionCommand()))
isOk=true;
setVisible(false);
}
}

I want to maintain session on my below Java Swing application

I am developing one java swing application for task remainder.Please find the below code for the same.But the problem is i am not able to maintain session here since i am using ScheduledExecutorService class which will help to trigger this Swing app one hour once.When triggering new one all changes has been made in previous session of app is gone.
Kindly help me on this and let me know how can i use session on my Swing application.
Example : If you run the below app yon can see two buttons when we click on button it will change color to "green" and status change to "Done" but when the application trigger after one minute all changes were erased launching as new one.
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Taskschdeuler {
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
final Runnable beeper = new Runnable()
{
public void run()
{
// do anything here that you want to execute in a scheduler.
Task r=new Task();
}
};
final ScheduledFuture<?> beeper1 = scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.MINUTES);
}
}
class Task extends JFrame implements ActionListener
{
JButton b1,b2,b3;
JLabel l1,l2;
public Task()
{
l1=new JLabel("Pending");
l2=new JLabel("Pending");
b1=new JButton("AVM DART");
b2=new JButton("HANDSHAKE");
b3=new JButton("Remind me later!!");
add(b1);
add(l1);
add(b2);
add(l2);
add(b3);
b1.setBackground(Color.PINK);
b2.setBackground(Color.PINK);
b3.setBackground(Color.CYAN);
b1.setPreferredSize(new Dimension(200, 50));
b2.setPreferredSize(new Dimension(200, 50));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() -300;
int y = 500;
setLocation(x, y);
setLayout(new FlowLayout());
setVisible(true);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(e.getSource()==b1)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l1.setText("Pending");
}
else
{
((Component)source).setBackground(Color.GREEN);
l1.setText(" Done");
}
}
if(e.getSource()==b2)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l2.setText("Pending");
} else
{
((Component)source).setBackground(Color.GREEN);
l2.setText(" Done");
}
}
if(e.getSource()==b3)
{
setVisible(false);
}
}
}

Converter Program for Hex to Dec and Binary

Given my code below, I'm a little confused as to what I am missing in order to allow it to function so that when the user inputs their hexadecimal value with a maximum of five digits, they will get their binary equivalent and the decimal equivalent. I thought the code at the bottom automatically converts given a certain number in hex. Also would it be difficult to store the binary values in an array?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.event.InputMethodListener;
import java.util.Scanner;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ConvertPanel {
public static void main(String[] args) {
JFrame frame = new JFrame ("Hexadecimal to Binary and Decimal.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new NumberConverter());
frame.pack();
frame.setVisible(true);
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodListener;
import java.util.Scanner;
import java.text.NumberFormat;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberConverter extends JPanel {
private JLabel binaryLabel = new JLabel();
private JLabel totalone = new JLabel();
private JLabel totaltwo = new JLabel();
private JLabel decimalLabel = new JLabel();
private JTextField hexdecString = new JTextField();
private JButton convert;
public NumberConverter() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(400, 300));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel converterName = new JLabel("Hexadecimal Input");
convert = new JButton ("Convert");
convert.addActionListener (new ButtonListener());
JPanel panelName = new JPanel(new GridLayout(2,2));
panelName.add(converterName);
panelName.add(hexdecString);
add(panelName, BorderLayout.NORTH);
add (convert);
JPanel totalPanel = new JPanel(new GridLayout(1,3));
totalPanel.add(new JLabel("Binary:"));
totalone = new JLabel("---- ---- ---- ---- ----");
totalPanel.add(totalone);
totalPanel.add(binaryLabel);
JPanel totalPanel2 = new JPanel(new GridLayout(2,3));
totalPanel2.add(new JLabel("Decimal:"));
totaltwo = new JLabel("------");
totalPanel2.add(totaltwo);
totalPanel2.add(decimalLabel);
JPanel south = new JPanel(new GridLayout(2,1));
south.add(totalPanel);
south.add(totalPanel2);
add(south, BorderLayout.SOUTH);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event){
Integer n = Integer.valueOf(hexdecString.getText(), 16);
decimalLabel.setText(String.valueOf(n));
binaryLabel.setText(Integer.toBinaryString(n));
} {
}
}
}

Look and feel is not updating in Swing JTabbedPane

I have created an application in Java Swing. I offer the option to change the look and feel of the application from a menu, but after adding a new tab in JTabbedPane, it is not getting updated with the new look and feel.
I have already used this code:
Window windows[] = Frame.getWindows();
for(Window window : windows) {
SwingUtilities.updateComponentTreeUI(window);
}
Leveraging #Andrew's example and this old thing, it seems to work for me.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
/**
* #see https://stackoverflow.com/a/11949899/230513
* #see https://stackoverflow.com/a/5773956/230513
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.addTab("Model", createPanel());
jtp.addTab("View", createPanel());
jtp.addTab("Control", createPanel());
f.add(createToolBar(f), BorderLayout.NORTH);
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
private static JToolBar createToolBar(final Component parent) {
final UIManager.LookAndFeelInfo[] available =
UIManager.getInstalledLookAndFeels();
List<String> names = new ArrayList<String>();
for (LookAndFeelInfo info : available) {
names.add(info.getName());
}
final JComboBox combo = new JComboBox(names.toArray());
String current = UIManager.getLookAndFeel().getName();
combo.setSelectedItem(current);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int index = combo.getSelectedIndex();
try {
UIManager.setLookAndFeel(
available[index].getClassName());
SwingUtilities.updateComponentTreeUI(parent);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
});
JToolBar bar = new JToolBar("L&F");
bar.add(combo);
return bar;
}
private static Box createPanel() {
Box panel = new Box(BoxLayout.X_AXIS);
JLabel label = new JLabel("Code: ", JLabel.LEFT);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
JTextArea text = new JTextArea(4, 16);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
text.append("#" + panel.hashCode());
text.append("\n#" + label.hashCode());
text.append("\n#" + label.hashCode());
panel.add(label);
panel.add(text);
return panel;
}
}

Hide a JButton (image) after click

I've create a program with a JButton(image) and a normal image, now if you click the normal button a image will show, now i have program that the JButton(image) will hide if you click the normal button but i dont work and i get a fault code
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import Controller.HideController;
import Controller.HomeController;
import Controller.SelectieController;
public class Selectie extends JFrame{
private static String Vermeer = "Vermeer";
private JLabel label, label1, label2;
private JButton keeper, kruis;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle("Jari");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
JLabel foto = new JLabel();
label1.add(foto);
kruis = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
kruis.setBorderPainted(false);
kruis.setBounds(40, 150, 188, 188);
label1.add(kruis);
keeper = new JButton("1. "+""+" Kenneth Vermeer");
Cursor cur = keeper.getCursor();
keeper.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
keeper.setBounds(20, 50, 186, 12);
keeper.setFocusable(false);
keeper.setBorderPainted(false);
keeper.setContentAreaFilled(false);
keeper.setFont(new Font("Arial",Font.PLAIN,17));
keeper.setForeground(Color.WHITE);
keeper.setActionCommand(Vermeer);
label.add(keeper);
SelectieController s1 = new SelectieController(keeper);
keeper.addActionListener(s1);
}
HideController h1 = new HideController(keeper, kruis);
{
keeper.addActionListener(h1);
}
}
The action listener class:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class HideController implements ActionListener {
private JButton keeper, logo;
private static String Vermeer = "Vermeer";
public HideController(JButton vermeer, JButton kruis)
{
keeper = vermeer;
logo = kruis;
//Kenneth Vermeer
try
{
keeper.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
logo.setVisible(false);
}
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
// Kenneth Vermeer
if (Vermeer.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
logo.setVisible(false);
}
});
}
}}
I hope someone could help me, thanks
If you want the button gone you can use window.remove(keeper). If you want no image but still want the button to be there, you can try logo = null, which will set the icon on logo to nothing, leaving you with a white box. If you are coding on Windows, you can add a background color with keeper.setBackgroundColor(Color.Blue) or whatever color your background is, however the Mac OS's look and feel will not allow this for some reason. (you can change the look and feel with, but that is fairly complicated) If you have a more complex background i would suggest taking a sample from the right point with a screenshot (with the button commented out in the code) and setting logo to that image.

Categories