Combining a constructor class with am main class - java

Can someone guide me on how can I combine these two classes into one file? One is a constructor class and the other one is a main.
Thanks;
Main Class:
public class JHelloDemo
{
public static void main(String[] args)
{
JHelloFrame frame = new JHelloFrame();
frame.setVisible(true);
}
}
Constructor class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHelloFrame extends JFrame implements ActionListener{
JLabel question = new JLabel("What is your name?");
Font bigFont = new Font("Arial", Font.BOLD, 16);
JTextField answer = new JTextField(10);
JButton pressMe = new JButton("Press me");
JLabel greeting = new JLabel("");
final int WIDTH = 275;
final int HEIGHT = 225;
public JHelloFrame(){
super("Hello Frame");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
question.setFont(bigFont);
greeting.setFont(bigFont);
add(question);
add(answer);
add(pressMe);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pressMe.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
String name = answer.getText();
String greet = "Hello, " + name;
greeting.setText(greet);
}
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JHelloFrame extends JFrame implements ActionListener{
JLabel question = new JLabel("What is your name?");
Font bigFont = new Font("Arial", Font.BOLD, 16);
JTextField answer = new JTextField(10);
JButton pressMe = new JButton("Press me");
JLabel greeting = new JLabel("");
final int WIDTH = 275;
final int HEIGHT = 225;
public JHelloFrame(){
super("Hello Frame");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
question.setFont(bigFont);
greeting.setFont(bigFont);
add(question);
add(answer);
add(pressMe);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pressMe.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
String name = answer.getText();
String greet = "Hello, " + name;
greeting.setText(greet);
}
public static void main(String[] args)
{
JHelloFrame frame = new JHelloFrame();
frame.setVisible(true);
}
}
There you go

You could simply move the main() method to JHelloFrame, which is the answer to your question. However, your existing design separates concerns, so I would leave it alone.
BTW, you should wrap frame.setVisible(true) in a Runnable and pass it to EventQueue.invokeLater(). See this question for more explanation.

Related

Connect jbutton to void class

I wanted to connect jcomp1 to the void class somma
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings({ "unused", "serial" })
public class Calcolatrice extends JPanel {
private JButton jcomp1;
public Calcolatrice() {
//construct components
jcomp1 = new JButton ("Somma");
}
void somma(){
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
And I tried with:
jcomp1.addActionListener(new ActionListener() {
public void somma(ActionEvent e) {
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
} );
But it doesn't seem to work...
Any ideas?
I just started coding and I thought this was an easy project but I'm already having troubles. For this reason could you explain as clear as possible please? Thank you.
This is an example of how to create a basic java swing frame with an interactive button.
public class Win extends JFrame implements ActionListener {
private JButton btn;
private JTextField tf;
private JTextField tf1;
private Label label;
private Panel panel;
public Win() {
btn = new JButton("Click");
tf = new JTextField(" ");
tf1 = new JTextField(" ");
label = new Label();
label.setPreferredSize(new Dimension(300,100));
panel = new Panel();
btn.addActionListener(this);
panel.add(btn);
panel.add(tf);
panel.add(tf1);
panel.add(label);
this.add(panel);
this.setSize(500, 500);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
label.setText(tf.getText()+" "+tf1.getText());
System.out.println("clicked");
}
}
You just need to instanciate the win class inside your main method.

java input JTextfield

I have a problem. The user input(inputUser) must be compared with the random number. Its kinda like a gamble program.
But I dont know how can I compare the input user string and the random number. And after that it is compared the output is in a dialog.
The input of the user comes with a string and the random number comes with a int. I already tried to convert the int to the string. but for some reason it doesnt work.
package gamble;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class Gamble extends JFrame {
public JLabel inputUser;
public JPanel panel;
Font myFont = new Font("Serif", Font.BOLD, 25);
Font rulesFont = new Font("Serif", Font.BOLD, 15);
public static void main(String[] args) {
Gamble GUI = new Gamble();
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(600, 600);
GUI.setResizable(false);
GUI.setVisible(true);
GUI.setLocationRelativeTo(null);
}
public Gamble(){
super("NUMERO");
JPanel panel = new JPanel();
panel.setLayout(null);
add(panel);
//nieuwe label
JLabel label = new JLabel("Raad het getal");
label.setLayout(null);
label.setBounds(250,10, 300, 30);
label.setFont(myFont);
panel.add(label);
//nieuwe label
JLabel rules = new JLabel("Gok een nummer tot en met 5");
rules.setBounds(225,40,300,30);
rules.setFont(rulesFont);
panel.add(rules);
//nieuw textfield
JTextField inputUser = new JTextField(100);
inputUser.setBounds(275,100,100,30);
inputUser.setFont(rulesFont);
inputUser.setBackground(Color.LIGHT_GRAY );
panel.add(inputUser);
thehandler handler = new thehandler();
inputUser.addActionListener(handler);
}
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event){
Random rand = new Random(); //random number
int n = rand.nextInt(5) + 1; //random number wordt gemaakt
int j = Integer.parseInt(inputUser.getText());
if (event.getSource()== inputUser){
if(n == j){
JOptionPane.showMessageDialog(null, "test");
}
}
else {
JOptionPane.showMessageDialog(null, "dfd");
}
}
}
}
There're some problems with the declaration of inputUser, just change the global declaration of it to JTextField and remove the local declaration of it.
The code should looks like below:
class Gamble extends JFrame {
public JTextField inputUser;
public JPanel panel;
Font myFont = new Font("Serif", Font.BOLD, 25);
Font rulesFont = new Font("Serif", Font.BOLD, 15);
public static void main(String[] args) {
Gamble GUI = new Gamble();
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(600, 600);
GUI.setResizable(false);
GUI.setVisible(true);
GUI.setLocationRelativeTo(null);
}
public Gamble(){
super("NUMERO");
JPanel panel = new JPanel();
panel.setLayout(null);
add(panel);
//nieuwe label
JLabel label = new JLabel("Raad het getal");
label.setLayout(null);
label.setBounds(250,10, 300, 30);
label.setFont(myFont);
panel.add(label);
//nieuwe label
JLabel rules = new JLabel("Gok een nummer tot en met 5");
rules.setBounds(225,40,300,30);
rules.setFont(rulesFont);
panel.add(rules);
//nieuw textfield
inputUser = new JTextField(100);
inputUser.setBounds(275,100,100,30);
inputUser.setFont(rulesFont);
inputUser.setBackground(Color.LIGHT_GRAY );
panel.add(inputUser);
thehandler handler = new thehandler();
inputUser.addActionListener(handler);
}
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event){
Random rand = new Random(); //random number
int n = rand.nextInt(5) + 1; //random number wordt gemaakt
int j = Integer.parseInt(inputUser.getText());
if (event.getSource()== inputUser){
if(n == j){
JOptionPane.showMessageDialog(null, "Yep, you're right");
}
else {
JOptionPane.showMessageDialog(null, "Nope nope nope, the number is " + n);
}
}
}
}
}

formatting JTextfields using another class

this is the code of the Gui Design class and below is the Class that provides functionality to the program. Im trying to get user input from the textfields so i can remove the text using the clearAll method and also save user input using the saveit method.I tried using nameEntry.setText(""); in the clearAll method but it wont work can someone help me please!
//Import Statements
import javax.swing.*;
import java.awt.*;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Customer extends JFrame {
Function fun = new Function();
public static void main(String[]args){
Customer.setLookAndFeel();
Customer cust = new Customer();
}
public Customer(){
super("Resident Details");
setSize(500,500);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
setLayout(two);
JPanel row1 = new JPanel();
JLabel name = new JLabel("First Name",JLabel.LEFT);
JTextField nameEntry = new JTextField("",20);
row1.add(name);
row1.add(nameEntry);
add(row1);
JPanel row2 = new JPanel();
JLabel surname = new JLabel("Surname ",JLabel.LEFT);
JTextField surnameEntry = new JTextField("",20);
row2.add(surname);
row2.add(surnameEntry);
add(row2);
JPanel row3 = new JPanel();
JLabel contact1 = new JLabel("Contact Details : Email ",JLabel.LEFT);
JTextField contact1Entry = new JTextField("",10);
FlowLayout newflow = new FlowLayout(FlowLayout.LEFT,10,30);
setLayout(newflow);
row3.add(contact1);
row3.add(contact1Entry);
add(row3);
JPanel row4 = new JPanel();
JLabel contact2 = new JLabel("Contact Details : Phone Number",JLabel.LEFT);
JTextField contact2Entry = new JTextField("",10);
row4.add(contact2);
row4.add(contact2Entry);
add(row4);
JPanel row5 = new JPanel();
JLabel time = new JLabel("Duration Of Stay ",JLabel.LEFT);
JTextField timeEntry = new JTextField("",10);
row5.add(time);
row5.add(timeEntry);
add(row5);
JPanel row6 = new JPanel();
JComboBox<String> type = new JComboBox<String>();
type.addItem("Type Of Room");
type.addItem("Single Room");
type.addItem("Double Room");
type.addItem("VIP Room");
row6.add(type);
add(row6);
JPanel row7 = new JPanel();
FlowLayout amt = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(amt);
JLabel amount = new JLabel("Amount Per Day ");
JTextField AmountField = new JTextField("\u20ac ",10);
row7.add(amount);
row7.add(AmountField);
add(row7);
JPanel row8 = new JPanel();
FlowLayout prc = new FlowLayout(FlowLayout.LEFT,100,10);
setLayout(prc);
JLabel price = new JLabel("Total Price ");
JTextField priceField = new JTextField("\u20ac ",10);
row8.add(price);
row8.add(priceField);
add(row8);
JPanel row9 = new JPanel();
JButton clear = new JButton("Clear");
row9.add(clear);
add(row9);
JPanel row10 = new JPanel();
JButton save = new JButton("Save");
save.addActionListener(fun);
row10.add(save);
add(row10);
//Adding ActionListners
nameEntry.addActionListener(fun);
clear.addActionListener(fun);
save.addActionListener(fun);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
//Import Statements
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import javax.swing.JOptionPane;
import java.awt.event.*;
//Class Name
public class Function implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Add Customer")) {
Login();
}
else if(command.equals("Register")){
Registration();
}
else if(command.equals("Exit")){
System.exit(0);
}
else if(command.equals("Clear")){
ClearAllFields();
}
else if(command.equals("Save")){
SaveIt();
}
}
public static void Login(){
Customer cust = new Customer();
}
public static void Registration(){
//Do Nothing
}
//This clears all the text from the JTextFields
public static void ClearAllFields(){
}
//This will save Info on to another Class
public static void SaveIt(){
}
}
Alternatively, you can make nameEntry known to the Function class by defining it before calling the constructor for Function and then passing it into the constructor, like:
JTextField nameEntry = new JTextField("",20);
Function fun = new Function(nameEntry);
Then, in Function, add nameEntry as a member variable of Function and make a constructor for Function which accepts nameEntry, (right after the "public class Function..." line), like:
JTextField nameEntry;
public Function(JTextField nameEntry) {
this.nameEntry = nameEntry;
}
Now, the following will compile:
public void ClearAllFields(){
nameEntry.setText("");
}
And, the Clear button will clear the name field.
Again as per comments, one simple way to solve this is to give the gui public methods that the controller (the listener) can call, and then pass the current displayed instance of the GUI into the listener, allowing it to call any public methods that the GUI might have. The code below is simpler than yours, having just one JTextField, but it serves to illustrate the point:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GUI extends JPanel {
private JTextField textField = new JTextField(10);
private JButton clearButton = new JButton("Clear");
public GUI() {
// pass **this** into the listener class
MyListener myListener = new MyListener(this);
clearButton.addActionListener(myListener);
clearButton.setMnemonic(KeyEvent.VK_C);
add(textField);
add(clearButton);
}
// public method in GUI that will do the dirty work
public void clearAll() {
textField.setText("");
}
// other public methods here to get text from the JTextFields
// to set text, and do whatever else needs to be done
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyListener implements ActionListener {
private GUI gui;
// use constructor parameter to set a field
public MyListener(GUI gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
gui.clearAll(); // call public method in field
}
}
A better and more robust solution is to structure your program in a Model-View-Controller fashion (look this up), but this would probably be overkill for this simple academic exercise that you're doing.

I can use getActionCommand to change the label content, but I can't use it to change the color?

So with the help of others here I finally managed to code a button that alternates the label "Hello World!" to "Hello Universe!" and back again. I used the code below, and used the same way to try and change the color, but it didn't work as expected. I've been searching for hours on this, but with no avail. Thank you for reading, anything helps!
Code:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton changetext;
protected JButton red;
protected JButton green;
private JLabel label;
public Javagame() {
add(changetext = new JButton("Button!"));
changetext.setPreferredSize(new Dimension(50, 50));
changetext.setActionCommand("change");
add(red = new JButton("Red"));
red.setPreferredSize(new Dimension(50, 50));
red.setActionCommand("changecolorRed");
add(green = new JButton("Green"));
green.setPreferredSize(new Dimension(50, 50));
green.setActionCommand("changecolorGreen");
changetext.addActionListener(this);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
add(changetext, BorderLayout.NORTH);
add(red, BorderLayout.WEST);
add(green, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
changetext.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
changetext.setActionCommand("change");
}
if ("changecolorRed".equals(e.getActionCommand())) {
label.setForeground(new Color(0xFF0000));
}
if ("changecolorGreen".equals(e.getActionCommand())) {
label.setForeground(new Color(0x009900));
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
JPanel panel = new JPanel(new BorderLayout());
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
You need to add ActionListeners to buttons for them to work.
This is usually done via a simple method call: red.addActionListener(someListener);
Also:
get rid of your setPreferredsize(...) method calls, and instead let components set their own size. At the most you can override getPreferredSize() if need be, but try to limit that.
Avoid having your GUI code implement your listener interfaces as that leads to confusing and difficult to manage code. Better to use anonymous inner listeners or private inner classes or stand alone listener classes.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaGame2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private static final Font LABEL_FONT = new Font("Arial", Font.BOLD, 20);
private static final Color[] FOREGROUNDS = { new Color(0x009900),
new Color(0x990000), new Color(0x000099), new Color(0x999900),
new Color(0x990099), new Color(0x009999) };
private static final String[] LABEL_TEXTS = { "Hello World!",
"Goodbye World!", "Hola Todo el Mundo!", "Hasta la Vista Baby!",
"Whatever!!" };
private JButton changetextButton;
private JButton changeColorButton;
private JLabel label;
private int labelTextIndex = 0;
private int foregroundIndex = 0;
public JavaGame2() {
label = new JLabel(LABEL_TEXTS[labelTextIndex], SwingConstants.CENTER);
label.setFont(LABEL_FONT);
label.setForeground(FOREGROUNDS[foregroundIndex]);
// example of anonymous inner ActionListener:
changetextButton = new JButton("Change Text");
changetextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
labelTextIndex++;
labelTextIndex %= LABEL_TEXTS.length;
label.setText(LABEL_TEXTS[labelTextIndex]);
}
});
// example of use of an anonymous AbstractAction:
changeColorButton = new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
foregroundIndex++;
foregroundIndex %= FOREGROUNDS.length;
label.setForeground(FOREGROUNDS[foregroundIndex]);
}
});
setLayout(new BorderLayout());
add(changetextButton, BorderLayout.NORTH);
add(changeColorButton, BorderLayout.SOUTH);
add(label, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JavaGame2 mainPanel = new JavaGame2();
JFrame frame = new JFrame("Java Game 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Applet not appearing full

I just created an applet
public class HomeApplet extends JApplet {
private static final long serialVersionUID = -7650916407386219367L;
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
// setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
RconSection rconSection = new RconSection();
rconSection.setOpaque(true);
// CommandArea commandArea = new CommandArea();
// commandArea.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setSize(400, 400);
tabbedPane.addTab("Rcon Details", rconSection);
// tabbedPane.addTab("Commad Area", commandArea);
setContentPane(tabbedPane);
}
}
where the fisrt tab is:
package com.rcon;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.Bean.RconBean;
import com.util.Utility;
public class RconSection extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -9021500288377975786L;
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
// private DynamicTree treePanel;
public RconSection() {
// super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new GridLayout(1,3));
panel1.add(testButton);
panel1.add(clearButton);
add(panel);
add(panel1);
// add(panel, BorderLayout.NORTH);
// add(panel1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(TEST_COMMAND)){
String ip = ipText.getText().trim();
if(!Utility.checkIp(ip)){
ipText.requestFocusInWindow();
ipText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Ip!!!");
return;
}
String port = portText.getText().trim();
if(port.equals("") || !Utility.isIntNumber(port)){
portText.requestFocusInWindow();
portText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Port!!!");
return;
}
String pass = rPassText.getText().trim();
if(pass.equals("")){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Enter Rcon Password!!!");
return;
}
RconBean rBean = RconBean.getBean();
rBean.setIp(ip);
rBean.setPassword(pass);
rBean.setPort(Integer.parseInt(port));
if(!Utility.testConnection()){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Rcon!!!");
return;
}else{
JOptionPane.showMessageDialog(this,"Correct Rcon!!!");
return;
}
}
else if(arg0.getActionCommand().equals(CLEAR_COMMAND)){
ipText.setText("");
portText.setText("");
rPassText.setText("");
}
}
}
it appears as
is has cropped some data how to display it full and make the applet non resizable as well. i tried setSize(400, 400); but it didnt helped the inner area remains the same and outer boundaries increases
Here's another variation on your layout. Using #Andrew's tag-in-source method, it's easy to test from the command line:
$ /usr/bin/appletviewer HomeApplet.java
// <applet code='HomeApplet' width='400' height='200'></applet>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class HomeApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private void createGUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Rcon1", new RconSection());
tabbedPane.addTab("Rcon2", new RconSection());
this.add(tabbedPane);
}
private static class RconSection extends JPanel implements ActionListener {
private static final String TEST_COMMAND = "test";
private static final String CLEAR_COMMAND = "clear";
private JTextField ipText = new JTextField();
private JTextField portText = new JTextField();
private JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel buttons = new JPanel(); // default FlowLayout
buttons.add(testButton);
buttons.add(clearButton);
add(panel, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
}
}
As I mentioned in a comment, this question is really about how to layout components in a container. This example presumes you wish to add the extra space to the text fields and labels. The size of the applet is set in the HTML.
200x130 200x150
/*
<applet
code='FixedSizeLayout'
width='200'
height='150'>
</applet>
*/
import java.awt.*;
import javax.swing.*;
public class FixedSizeLayout extends JApplet {
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initGui();
}
});
}
private void initGui() {
JTabbedPane tb = new JTabbedPane();
tb.addTab("Rcon Details", new RconSection());
setContentPane(tb);
validate();
}
}
class RconSection extends JPanel {
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout(3,3));
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
panel1.add(testButton);
panel1.add(clearButton);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container c = new RconSection();
JOptionPane.showMessageDialog(null, c);
}
});
}
}
Size of applet viewer does not depend on your code.
JApplet is not window, so in java code you can't write japplet dimensions. You have to change run settings. I don't know where exactly are in other ide's, but in Eclipse you can change dimensions in Project Properties -> Run/Debug settings -> click on your launch configurations file (for me there were only 1 - main class) -> edit -> Parameters. There you can choose width and height for your applet. save changes and you are good to go

Categories

Resources