I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.
Related
I am supposed to implement an application to the user that has 2 buttons(Increment/decrement) and a label. When increment is pressed the number increases and decreases by one when decrement is pressed. The number starts at 50. I have it to where it shows the buttons and they work, but they work on 2 different variables, so their is 2 number printed to the screen instead of 1. My question is how can i make the button act on only one number. I have seen people use push etc. but is there another way to do this by passing in a value to both or something? Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonModifier
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
FlowLayout flow = new FlowLayout();
frame.getContentPane().setLayout(flow);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setTitle("Button Modifier");
IncrementPanel panel = new IncrementPanel();
DecrementPanel panel1 = new DecrementPanel();
frame.add(panel);
frame.add(panel1);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecrementPanel extends JPanel
{
private JButton button1;
private JLabel label;
private int number = 50;
public DecrementPanel()
{
button1 = new JButton("Decrement");
button1.addActionListener(new /*DecrementPanel.*/ButtonListener());
label = new JLabel("" + number);
this.add(button1);
this.add(label);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//int increment = 50;
number--;
label.setText("" + number);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class IncrementPanel extends JPanel
{
private JButton button;
private JLabel label;
int number = 50;
public IncrementPanel()
{
button = new JButton("Increment");
button.addActionListener(new ButtonListener());
label = new JLabel("" + number);
this.add(button);
this.add(label);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//int increment = 50;
number++;
label.setText("" + number);
}
}
}
I am supposed to implement an application to the user that has 2 buttons(Increment/decrement) and a label."
Then why do you have two?
IncrementPanel panel = new IncrementPanel();
DecrementPanel panel1 = new DecrementPanel();
Just use one and change the text on that one
Should be more like this
public class ButtonModifier extends JFrame {
private JLabel numberLabel = new JLable("50");
private JButton decrease = new JButton("-1");
private JButton increase = new JButton("+1");
private static int num = 50;
public ButtonModifier(){
setLayout(new GridLayout(1, 3));
add(increase);
add(numberLabel);
add(decrease);
increase.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
num++;
numLabel.setText("" + num);
}
});
decrease.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
num--;
numLabel.setText("" + num);
}
});
}
public static void main(String[] args){
JFrame frame = ButtonModifier();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setTitle("Button Modifier");
frame.setVisible(true);
}
}
You should have one JLabel which will display the only number in your program.
Then your two buttons will do operations on that number and update the label.
Your mistake is that each Panel has its own number and its own Label to display the number.
public class ButtonModifier {
private static int number = 50;
private static JLabel label;
public static void main(String[] args) {
JFrame frame = new JFrame();
label = new JLabel("" + number);
// <SNIP>
JButton increment = new JButton("Increment");
increment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
number++;
label.setText("" + number);
}
}
JButton decrement = new JButton("Increment");
increment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
number--;
label.setText("" + number);
}
}
frame.add(label);
frame.add(increment);
frame.add(decrement);
frame.setVisible(true);
}
}
An important note: Swing is not thread-safe, and all the operations with GUI components must be performed on Event Dispatch Thread. So your main must actually look this way:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Here you create the frame and all the components
}
});
}
Take a look at this program :
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class IncDecApp extends JFrame {
private JButton incBtn = new JButton("Increment");
private JButton decBtn = new JButton("Decrement");
private JPanel lowPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JLabel showLbl = new JLabel("00", JLabel.CENTER);
private Font myFont = new Font("Tahoma", Font.BOLD, 60);
private int valueInt;
public IncDecApp() {
setTitle("IncDec Application =)");
setDefaultCloseOperation(EXIT_ON_CLOSE);
lowPanel.add(incBtn);
lowPanel.add(decBtn);
incBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueInt = Integer.parseInt(showLbl.getText());
valueInt++;
if (valueInt >= 10) {
showLbl.setText(String.valueOf(valueInt));
} else {
showLbl.setText("0" + String.valueOf(valueInt));
}
}
});
decBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
valueInt = Integer.parseInt(showLbl.getText());
if (valueInt > 0) {
valueInt--;
}
if (valueInt >= 10) {
showLbl.setText(String.valueOf(valueInt));
} else {
showLbl.setText("0" + String.valueOf(valueInt));
}
}
});
showLbl.setFont(myFont);
add(showLbl, BorderLayout.CENTER);
add(lowPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new IncDecApp();
}
}
Create the JLabel in the main function. Have the incrementPanel and DecrementPanel classes constructors take a JLabel as an argument that they store as a private variable. The ButtonListeners csn also be passed the JLabel as an argument. Now the button listeners csn update a common JLabel.
Now, you can improve things by combining the code of IncrementPanel and DecrementPanel classes by passing an int in the constructor indicating the increment of +1 or -1.
A quick and dirty way to implement the functionality is through the use of anonymous classes implementing button listeners within a single monolithic class.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonApplet extends Applet implements ActionListener{
Button buttonInc, buttonDec;
int x=0;
public void init(){
buttonInc=new Button("Increment");
buttonDec=new Button("Decrement");
buttonInc.addActionListener(this);
buttonDec.addActionListener(this);
add(buttonInc);
add(buttonDec);
}
public void paint(Graphics g){
g.drawString("Count is : "+x,50,100);
}
public void actionPerformed(ActionEvent ev){
if(ev.getSource() == buttonInc)
{
x++;
repaint();
}
else if(ev.getSource() == buttonDec){
x--;
repaint();
}
}
}
Make Java GUI Application using AWT
You are required to make one label (Count), one textfield, one button (Increment), one button (Decrement) and one button (Close)
When the increment button is clicked, you need to increment the value in textfield, value should be incremented again and again when the button is clicked
When the decrement button is clicked, you need to decrement the value in textfield, value should be decremented again and again when the button is clicked
When the close button is clicked, you need to close the AWT Frame
Okay I can get text fields and normal text and even images to show but I can not get a button to show. I am not sure what I am doing wrong because I have done the same steps for the rest. Any help would be great thanks!
package EventHandling2;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import EventHandling.GUITest;
public class EventMain extends JFrame{
private JLabel label;
private JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
//gui.setSize(600, 300);
gui.setVisible(true);
gui.setTitle("Button Test");
}
public void EventMain(){
setLayout(new FlowLayout());
button = new JButton ("click for text");
add(button);
label = new JLabel ("");
add(label);
Events e = new Events();
button.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
The problem is with the method: void EventMain()
Constructor has NO return type. Just remove "void". The code will work just fine.
Your actionListener(e) contains a minor control structure error:
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
Change to:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Now you can see words");
}
}
First off, you have to remove void keyword in EventMain's constructor. Then, creating JPanel and add components into it, then add the JPanel to the JFrame.contentPane.
The following code should work:
public class EventMain extends JFrame {
private final JLabel label;
private final JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x
// close program
gui.setSize(600, 300);
gui.setTitle("Button Test");
gui.setVisible(true);
}
public EventMain() {
// setLayout(new FlowLayout());
JPanel panel = new JPanel(new FlowLayout());
button = new JButton("click for text");
panel.add(button);
label = new JLabel("");
panel.add(label);
Events e = new Events();
button.addActionListener(e);
this.getContentPane().add(panel);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
I have a frame that when i click ok button on tester2 frame, tester1 frame should be seen and when click showbumber button, a random number should be displayed in my label.
But i can't see this generated number while i use sleep method!
Thank for help.
public class tester2 extends JFrame implements ActionListener {
public tester2() {
setTitle("Hello");
setLayout(new FlowLayout());
JButton okButton = new JButton("Ok");
okButton.addActionListener(this);
add(okButton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
tester1 tester1 = new tester1(tester2.this);
tester1.setVisible(true);
}
public static void main(String[] args) {
new tester2().setVisible(true);
}
}
tester 1:
public class tester1 extends JDialog implements ActionListener {
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel(" ");
this.add(showButton);
this.add(lbl1);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showButton) {
GenerateNumber();
tester1.this.dispose();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
try {
Thread.sleep(1000);
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
}
}
If your intention is to close the second frame automatically after a short delay, you should use a javax.swing.Timer instead.
Blocking the EDT will stop it from (amongst other things) processing repaint request, which means your UI can't be updated when you can Thread.sleep
Instead you should use a javax.swing.Timer
public void GenerateNumber() {
Random rnd1 = new Random();
try {
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
timer.setRepeats(false);
timer.start();
}
I don't if your dialog shows the showButton and Label before. Because i have to add a panel in order to show them. After that you need a Timer Class to deal with auto dispose.
Your tester1 look now like this
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class tester1 extends JDialog implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
this.add(jPanel);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel();
jPanel.add(showButton, BorderLayout.NORTH);
jPanel.add(lbl1, BorderLayout.CENTER);
this.setBounds(40, 50, 300, 400);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == showButton) {
GenerateNumber();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
lbl1.setText(String.valueOf(rnd1.nextInt(1000000)));
Timer timer = new Timer(1000 * 1, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
timer.setRepeats(false);
timer.start();
}
}
I have a problem, I have been making a Swing application.
My question is about how to handle Jbutton like a JOptionPane, if it's possible?
I want handle all of the buttons similarly to JOptionpane button, but our message written in main function System.out.println("this line executes...how to prevent..");
This function is to display the message, until Jframe is visible.
Can anyone let me know how to prevent & how to handle button functionality? Especially when it executes further when I click the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
JLabel name=new JLabel("Name:");
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(false);
JPanel namePanel = new JPanel();
namePanel.add(name);
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
warningLabel.setForeground(Color.red);
add(warningLabel, BorderLayout.NORTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty :"+name.getText());
warningLabel.setBackground(WARNING_COLOR);
//firstNameField.setText("sorry");
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setSize(200, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGui();
System.out.println("this line executes...how to prevent..");
}
}
Basically, you have something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
System.err.println("Executed once the button has been clicked");
}
}
And you want the line System.err.println("Executed once the button has been clicked"); to be executed when the button is pressed (which is not the case here above).
The solution is actually very simple: you move the code to execute after the button click in another method (see below the proceed() method) and you invoke that line from an ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
proceed();
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
protected void proceed() {
System.err.println("Executed once the button has been clicked");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
}
}
Well, the question is not very much clear,but from your comment,you dont want to do any thing till a JButton is clicked? Or you want to preform a task after clicking of a button?
If that is so, dont put your further code inside your main block, call a function from actionPerformed block.Something like this:
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
display();///////////this is the function containing further code
}
}
//this is display
public void display()
{
System.out.println("this line executes...how to prevent..");
}
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