I have the following class which is a simple gui, and I would like to make it an applet so it can be displayed in the browser. I know how to embed the code into an html page(got that done)... but how can make my class an applet? Also, I assuming I don't need a web server just to display the applet in my browser...
package tester1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanelTest implements ActionListener {
JFrame frame;
JLabel inputLabel;
JLabel outputLabel;
JLabel outputHidden;
JTextField inputText;
JButton button;
JButton clear;
JButton about;
public PanelTest() {
frame = new JFrame("User Name");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2, 10, 10));
//creating first row
JPanel row1 = new JPanel();
inputLabel = new JLabel("Your Name");
inputText = new JTextField(15);
// FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row1.setLayout(flow1);
row1.add(inputLabel);
row1.add(inputText);
frame.add(row1);
//creating second row
JPanel row2 = new JPanel();
button = new JButton("Display");
clear = new JButton("Clear");
about = new JButton("About");
button.addActionListener(this);
clear.addActionListener(this);
about.addActionListener(new displayAbout());
row2.add(button);
row2.add(clear);
row2.add(about);
frame.add(row2);
//creating third row
JPanel row3 = new JPanel();
outputLabel = new JLabel("Output:", JLabel.LEFT);
outputHidden = new JLabel("", JLabel.RIGHT);
// FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row3.setLayout(flow2);
row3.add(outputLabel);
row3.add(outputHidden);
frame.add(row3);
frame.pack();
frame.setVisible(true);
}
//same method listen for two different events
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Display")) {
outputHidden.setText(inputText.getText());
}
if(command.equals("Clear")) {
outputHidden.setText("");
inputText.setText("");
}
}
//another way to listen for events
class displayAbout implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Username 1.1 \n by Jorge L. Vazquez");
}
}
public static void main(String[] args) {
PanelTest frameTest = new PanelTest();
}
}
Use a JApplet rather than a JFrame. Make sure you read the relevant Java Tutorial, which covers the applet lifecycle methods like init, start, stop, and destroy.
As a side note, you should not be building your UI outside of the event dispatch thread.
Use a JApplet instead of a JFrame like veer said, but you must also remove frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, frame.pack();, and frame.setVisible(true);
Also, replace main(String[] args) with init().
Related
I am Completely new to writing Java. I am creating an interface that gathers a list of all the internet connections in the area. The user selects one on them, enters the password then the person can connect to the password. I have a problem with the Password field... It is to big for a password box.
How do I fix that? Here is the code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Network_Interface
{
JFrame frame;
JPanel panel;
public static void main (String[] args)
{
Network_Interface OBJECT_GUI = new Network_Interface();
OBJECT_GUI.INIT();
}
public void INIT()
{
//frame and panel
JFrame FRAME = new JFrame();
JPanel PANEL = new JPanel();
//init fields and labels
JButton BUTTON_REFRESH = new JButton("Refesh List");
JButton BUTTON_CONNECT = new JButton("Connect to network");
JPasswordField FIELD_PASSWORD = new JPasswordField(15);
JLabel LABEL_PASSWORD = new JLabel("Enter Password of selected newtork.");
JList LIST_NETWORKS = new JList(GET_NETWORKS());
//event listeners
BUTTON_REFRESH.addActionListener(new REFRESH_LISTENER());
BUTTON_CONNECT.addActionListener(new CONNECT_LISTENER());
//panel handling
PANEL.setLayout(new BoxLayout(PANEL, BoxLayout.Y_AXIS));
PANEL.add(LIST_NETWORKS);
PANEL.add(BUTTON_REFRESH);
PANEL.add(LABEL_PASSWORD);
PANEL.add(FIELD_PASSWORD);
PANEL.add(BUTTON_CONNECT);
FRAME.getContentPane().add(BorderLayout.CENTER, PANEL);
FRAME.setSize(500,500);
FRAME.setVisible(true);
}
public String[] GET_NETWORKS()
{
//read file
String[] ARRAY_NETWORKS= new String[2];
ARRAY_NETWORKS[0] = "Frnkthtnk100";
ARRAY_NETWORKS[1] = "CheesecakeFactory";
return ARRAY_NETWORKS;
}
class REFRESH_LISTENER implements ActionListener
{
public void actionPerformed(ActionEvent EVENT)
{
//idk to do at this point
}
}
class CONNECT_LISTENER implements ActionListener
{
public void actionPerformed(ActionEvent EVENT)
{
//IDk at this point
}
}
}
1) Easy way : replace FRAME.setSize(500,500); by FRAME.pack();.
It will adjust the frame to the size of the components.
But it will change the size of the frame.
2)If you want to keep the frame size, you can specify the maximum size of JPasswordField FIELD_PASSWORD so that it doesn't be extended to the maximum in the JPanel.
JPasswordField FIELD_PASSWORD = new JPasswordField(15);
FIELD_PASSWORD.setMaximumSize(new Dimension(FIELD_PASSWORD.getMaximumSize().width, FIELD_PASSWORD.getMinimumSize().height));
When i run this program sometimes shows me all buttons, but sometimes only 2 or 3 or 4 or 5 or even just 1.. why is that??
I really do not get it. There should always be 6 buttons, but it doesnt show them. Is there any logical reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class testnet
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Knjigarna");
frame.setVisible(true);
frame.setSize(800,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("Prikazi vse");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("Prikazi knjigo");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Dodaj knjigo");
panel.add(button3);
button3.addActionListener (new Action3());
JButton button4 = new JButton("Brisi knjigo");
panel.add(button4);
button4.addActionListener (new Action4());
JButton button5 = new JButton("Uredi knjigo");
panel.add(button5);
button5.addActionListener (new Action5());
JButton button6 = new JButton("Izhod");
panel.add(button6);
button6.addActionListener (new Action6());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("Pikaz vseh knjig");
frame2.setVisible(true);
frame2.setSize(500,800);
JLabel label = new JLabel("Seznam vseh knjig:");
JPanel panel = new JPanel();
JTextField text1=new JTextField("Naslov: ");
JTextField text2=new JTextField("Avtor: ");
frame2.add(panel);
panel.add(label);
panel.add(text1);
panel.add(text2);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("Prikaz knjige");
frame3.setVisible(true);
frame3.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige:");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Dodajanje knjige");
frame4.setVisible(true);
frame4.setSize(600,300);
JLabel label = new JLabel("Vpisi podtke o knjigi");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
static class Action4 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame5 = new JFrame("Brisanje knjige");
frame5.setVisible(true);
frame5.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis brisati");
JPanel panel = new JPanel();
frame5.add(panel);
panel.add(label);
}
}
static class Action5 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame6 = new JFrame("Urejanje knjige");
frame6.setVisible(true);
frame6.setSize(600,300);
JLabel label = new JLabel("Vpisi naslov knjige, ki jo zelis urejati");
JPanel panel = new JPanel();
frame6.add(panel);
panel.add(label);
}
}
static class Action6 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
System.exit(0);
}
}
}
try something with layout. JFrame and or remove managed by inside with a content pane. content pane default layout is BorderLayout. so you need to try border layout stuff.
or you can try this code in you main method
frame.setLayout(new FlowLayout());
this will add component by one by one.
for more about layout you can get in here
This is just a fix and not really an explanation of why the problem is occurring.
Call frame.revalidate() after adding all the buttons.
From the Java Docs,
public Component add(Component comp)
This method
changes layout-related information, and therefore, invalidates the
component hierarchy. If the container has already been displayed, the
hierarchy must be validated thereafter in order to display the added
component.
For some reason the AddListener class below doesn't work, and I keep getting a number format exception. Could anyone please tell me the reason for this. It seems to me as if it should work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculator extends JFrame {
JFrame theFrame = this;
JTextField addField; // Declaring this here so that you can access the variable from other places. MAKE SURE TO NOT DECLARE THIS AGAIN IN THE CONSTRUCTOR
JTextField totalField;
public BabyCalculator() {
//You set this up so that you can refer to the frame using the inner class below.
setDefaultCloseOperation(EXIT_ON_CLOSE);
setName("Baby Calculator");
setLayout(new GridLayout(3, 0));
//add
JLabel addLabel = new JLabel("Amount to add:");
addField = new JTextField(10);
JButton addButton = new JButton("add");
addButton.addActionListener(new AddListener());
//multiply
JLabel multiplyLabel = new JLabel("Amount to multiply:");
JTextField multiplyField = new JTextField(10);
JButton multiplyButton = new JButton("multiply");
//total
JLabel totalLabel = new JLabel("Total");
totalField = new JTextField(10);
totalField.setEditable(false);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
//Create Panels
JPanel topRow = new JPanel(new BorderLayout());
JPanel middleRow = new JPanel(new BorderLayout());
JPanel bottomRow = new JPanel(new FlowLayout());
//Add the top Row
topRow.add(addLabel, BorderLayout.WEST);
topRow.add(addField, BorderLayout.CENTER);
topRow.add(addButton, BorderLayout.EAST);
add(topRow);
middleRow.add(multiplyLabel, BorderLayout.WEST);
middleRow.add(multiplyField, BorderLayout.CENTER);
middleRow.add(multiplyButton, BorderLayout.EAST);
add(middleRow);
bottomRow.add(totalLabel);
bottomRow.add(totalField);
bottomRow.add(stopButton);
add(bottomRow);
pack();
setVisible(true);
}
public class AddListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String addFieldText = addField.getText();
String totalFieldText = totalField.getText();
double addAmount = Double.parseDouble(addFieldText);
double total = Double.parseDouble(totalFieldText);
total += addAmount;
totalField.setText(total + "");
}
}
//end class AddListener
public class StopListener implements ActionListener {//this is an inner class
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(theFrame, "You Clicked the stop button");
}//end class StopListener
}
public static void main(String[] args) {
JFrame newFrame = new BabyCalculator();
}
}
Note: The problem in the code is definitely related to the AddListener. Whenever I click the add button in the GUI I get an exception.
The problem is with the totalFieldText, it's default value is blank, meaning that when you try and convert to a double value, it causes a NumberFormatException
Try giving it a default value of 0, for example
totalField = new JTextField("0", 10);
You might also like to take a look at How to Use Spinners and How to Use Formatted Text Fields which will make your life easier
I am working on a project for my college course. I was just wondering if anyone knew how to add a scrollBar to a JTextArea. At present I have the GUI laid out correctly, the only thing missing is the scroll bar.
This is what the GUI looks like. As you can see on the second TextArea I would like to add the Scrollbar.
This is my code where I create the pane. But nothing seems to happen... t2 is the JTextArea I want to add it to.
scroll = new JScrollPane(t2);
scroll.setBounds(10,60,780,500);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
Any help would be great, thanks!
The Scroll Bar comes when your text goes beyond the bounds of your view area. Don't use Absolute Positioning, for such a small talk at hand, always prefer Layout Managers, do read the first para of the first link, to know the advantage of using a Layout Manager.
What you simply need to do is use this thingy :
JTextArea msgArea = new JTextArea(10, 10);
msgArea.setWrapStyleWord(true);
msgArea.setLineWrap(true);
JScrollPane msgScroller = new JScrollPane();
msgScroller.setBorder(
BorderFactory.createTitledBorder("Messages"));
msgScroller.setViewportView(msgArea);
panelObject.add(msgScroller);
Here is a small program for your understanding :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextAreaScroller
{
private JTextArea msgArea;
private JScrollPane msgScroller;
private JTextArea logArea;
private JScrollPane logScroller;
private JButton sendButton;
private JButton terminateButton;
private Timer timer;
private int counter = 0;
private String[] messages = {
"Hello there\n",
"How you doing ?\n",
"This is a very long text that might won't fit in a single line :-)\n",
"Okay just to occupy more space, it's another line.\n",
"Don't read too much of the messages, instead work on the solution.\n",
"Byee byee :-)\n",
"Cheers\n"
};
private ActionListener timerAction = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (counter < messages.length)
msgArea.append(messages[counter++]);
else
counter = 0;
}
};
private void displayGUI()
{
JFrame frame = new JFrame("Chat Messenger Dummy");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(0, 1, 5, 5));
logArea = new JTextArea(10, 10);
logArea.setWrapStyleWord(true);
logArea.setLineWrap(true);
logScroller = new JScrollPane();
logScroller.setBorder(
BorderFactory.createTitledBorder("Chat Log"));
logScroller.setViewportView(logArea);
msgArea = new JTextArea(10, 10);
msgArea.setWrapStyleWord(true);
msgArea.setLineWrap(true);
msgScroller = new JScrollPane();
msgScroller.setBorder(
BorderFactory.createTitledBorder("Messages"));
msgScroller.setViewportView(msgArea);
centerPanel.add(logScroller);
centerPanel.add(msgScroller);
JPanel bottomPanel = new JPanel();
terminateButton = new JButton("Terminate Session");
terminateButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (timer.isRunning())
timer.stop();
else
timer.start();
}
});
sendButton = new JButton("Send");
bottomPanel.add(terminateButton);
bottomPanel.add(sendButton);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(bottomPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(1000, timerAction);
timer.start();
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new JTextAreaScroller().displayGUI();
}
});
}
}
Here is the outcome of the same :
The scroll bar by default will only be shown when the content overfills the available viewable area
You can change this via the JScrollPane#setVerticalScrollBarPolicy method, passing it ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
import java.awt.Frame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class IndicatorWindow implements ItemListener {
JRadioButton RMA, EMA, SMA, Williams, Stochastic;
JPanel IndPan, RadioPanel, title;
JLabel Lab;
JButton OK;
public JPanel createContentPane() {
JPanel GUI = new JPanel();
GUI.setLayout(null);
title = new JPanel();
title.setLayout(null);
title.setLocation(0, 0);
title.setSize(500, 145);
GUI.add(title);
Lab = new JLabel("Please Select Indicator Type");
Lab.setLocation(5, 0);
Lab.setSize(200, 30);
title.add(Lab);
ButtonGroup bg1 = new ButtonGroup();
RadioPanel = new JPanel();
RadioPanel.setLayout(null);
RadioPanel.setLocation(10, 30);
RadioPanel.setSize(190, 220);
GUI.add(RadioPanel);
RMA = new JRadioButton("RMA");
RMA.setLocation(0, 0);
RMA.addItemListener(this);
RMA.setSize(110, 20);
bg1.add(RMA);
RadioPanel.add(RMA);
EMA = new JRadioButton("EMA");
EMA.setLocation(0, 30);
EMA.addItemListener(this);
EMA.setSize(110, 20);
bg1.add(EMA);
RadioPanel.add(EMA);
SMA = new JRadioButton("SMA");
SMA.setLocation(0, 60);
SMA.addItemListener(this);
SMA.setSize(110, 20);
bg1.add(SMA);
RadioPanel.add(SMA);
Stochastic = new JRadioButton("Stochastic");
Stochastic.setLocation(0, 90);
Stochastic.addItemListener(this);
Stochastic.setSize(110, 20);
bg1.add(Stochastic);
RadioPanel.add(Stochastic);
Williams = new JRadioButton("Williams");
Williams.setLocation(0, 120);
Williams.addItemListener(this);
Williams.setSize(110, 20);
bg1.add(Williams);
RadioPanel.add(Williams);
OK = new JButton();
OK.setText("Confirm");
OK.setLocation(45, 150);
OK.addItemListener(this);
OK.setSize(90, 30);
RadioPanel.add(OK);
//GUI.setOpaque(true);
return GUI;
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == RMA) {
System.out.print("Browse");
} else if (source == EMA) {
System.out.print("EMA");
} else if (source == SMA) {
System.out.print("SMA");
} else if (source == Williams) {
System.out.print("Williams");
} else if (source == Stochastic) {
System.out.print("Stochastic");
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
IndicatorWindow ind = new IndicatorWindow();
frame.setContentPane(ind.createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(200, 250);
frame.setLayout(null);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setState(Frame.NORMAL);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
My problem is that when i compile and run this code, the jFrame appears but there is only one problem, 3 JRadioButtons dont appear until you put your mouse over them. The RMA and Williams radiobuttons appear, the 3 in the middle do not though, any thoughts on why this is?
http://i.stack.imgur.com/gNnIb.jpg
You should be using layout managers. People think using a "null layout" is easier, but it is not and you are more prone to having errors with your code. Layout managers will position and size components properly to make sure all components are displayed. Sometimes you even use multiple different layout managers to achieve the layout you desire.
Your problem in this case is that you have two components occupying the same space in your container. So one component gets painted over top of the other. After you mouse over your radio button, the button is repainted because of the rollover effect of the button. However, now try resizing the frame and the radio buttons will disappear because all the components are repainted and the component is painted over top of the buttons again.
The following line of code is the problem:
// title.setSize(500, 145);
title.setSize(500, 20);
But the real solution is to rewrite the code and use layout managers. While you are at it use proper Java naming conventions. Variable names do NOT start with an uppercase letter. You got "title" and "bg1" correct. So fix "EMA", "RMA" etc...
#camickr is correct. Note how using layout managers (and a little re-factoring) can actually simplify your code. Also, the relevant tutorial suggests using an action listener, rather than an item listener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/5255337 */
public class IndicatorWindow implements ActionListener {
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
JRadioButton rma, ema, sma, stochastic, williams;
ButtonGroup bg = new ButtonGroup();
public JPanel createContentPane() {
JPanel gui = new JPanel(new BorderLayout());
JPanel title = new JPanel();
JLabel lab = new JLabel("Please Select Indicator Type");
title.add(lab);
gui.add(title, BorderLayout.NORTH);
createRadioButton(rma, "RMA");
createRadioButton(ema, "EMA");
createRadioButton(sma, "SMA");
createRadioButton(stochastic, "Stochastic");
createRadioButton(williams, "Williams");
gui.add(radioPanel, BorderLayout.CENTER);
JButton ok = new JButton();
ok.setText("Confirm");
ok.addActionListener(this);
radioPanel.add(ok);
return gui;
}
private void createRadioButton(JRadioButton jrb, String name) {
jrb = new JRadioButton(name);
bg.add(jrb);
jrb.addActionListener(this);
radioPanel.add(jrb);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
frame.add(new IndicatorWindow().createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You should add your JRadioButtons with a method:
private void bgAdd (String name, int y)
{
JRadioButton rb = new JRadioButton (name);
rb.setLocation (0, y);
rb.addItemListener (this);
rb.setSize (110, 19);
bg1.add (rb);
radioPanel.add (rb);
}
Calling code:
bgAdd ("RMA", 0);
bgAdd ("EMA", 30);
bgAdd ("SMA", 60);
bgAdd ("Stochastic", 90);
bgAdd ("Williams", 120);
Action:
public void itemStateChanged (ItemEvent e) {
Object button = e.getItemSelectable ();
String source = ((JRadioButton) button).getText ();
System.out.print (source + " ");
}
Then add BoxLayout to the page, for example.