After updating JComboBox, how to refresh length of box - java

I am trying to create a way to update a JComboBox so that when the user enters something into the text field, some code will process the entry and update the JComboBox accordingly.The one issue that I am having is I can update the JComboBox, but the first time it is opened, the box has not refresh the length of the options in it and as seen in the code below it displays extra white space. I do not know if there is a better different way to do this, but this is what I came up with.
Thanks for the help,
Dan
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Catch{
public static JComboBox dropDown;
public static String dropDownOptions[] = {
"Choose",
"1",
"2",
"3"};
public static void main(String[] args) {
dropDown = new JComboBox(dropDownOptions);
final JTextField Update = new JTextField("Update", 10);
final JFrame frame = new JFrame("Subnet Calculator");
final JPanel panel = new JPanel();
frame.setSize(315,430);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Update.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
}
public void focusLost(FocusEvent arg0) {
dropDown.removeAllItems();
dropDown.insertItemAt("0", 0);
dropDown.insertItemAt("1", 1);
dropDown.setSelectedIndex(0);
}
});
panel.add(Update);
panel.add(dropDown);
frame.getContentPane().add(panel);
frame.setVisible(true);
Update.requestFocus();
Update.selectAll();
}
}

1) JTextField listening for ENTER key from ActionListener
2) remove FocusListener
3) example about add new Item as last Item from JTextField to the JList, only you have to modify for JComboBox and add method insertItemAt() correctly
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListBottom2 {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JTextField textField = new JTextField("Use Enter to Add");
private JPanel panel = new JPanel(new BorderLayout());
public ListBottom2() {
model.addElement("First");
list.setVisibleRowCount(5);
panel.setBackground(list.getBackground());
panel.add(list, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(200, 100));
frame.add(scrollPane);
frame.add(textField, BorderLayout.NORTH);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField textField = (JTextField) e.getSource();
DefaultListModel model = (DefaultListModel) list.getModel();
model.addElement(textField.getText());
int size = model.getSize() - 1;
list.scrollRectToVisible(list.getCellBounds(size, size));
textField.setText("");
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ListBottom2 frame = new ListBottom2();
}
});
}
}

Related

How to make a Blank JList at a specified size? Without empty elements

I am trying to create a BLANK JList for the user to see befor elements are added. Over all what is happening is I am using JFileChooser to select txt documents to be added to a list, then the vowels in each txt document are counted and displayed in the other list. The list must be visible before the user selects anything and the list must be blank. Yes there are two empty JList but obviously if I can get help with one the other is easy. So far nowhere on the internet touches on this particular subject.
Setting row count(visible) does not work, nor setsize(). Unless I am using it wrong. Please explain with examples. Thanks in advance!
An example below:
Code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class VowelCounterApp extends JFrame implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JScrollPane scrollPane = new JScrollPane();
JList selectList = new JList();
JList showList = new JList();
JFileChooser fileChooser = new JFileChooser();
JButton addFiles = new JButton("Add Files");
JButton process = new JButton("Process");
JButton clear = new JButton("Clear");
JButton help = new JButton("Help");
public VowelCounterApp()
{
JFrame appWindow = new JFrame("Vowel Counter");
appWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
appWindow.setSize(1500, 600);
appWindow.setLayout(new BorderLayout());
appWindow.setVisible(true);
appWindow.add(panel1, BorderLayout.WEST);
appWindow.add(panel2, BorderLayout.EAST);
panel1.add(selectList);
selectList.add(scrollPane);
panel2.add(showList);
showList.add(scrollPane);
}
public void actionPerformed(ActionEvent e)
{
}
public static void main(String[] args)
{
new VowelCounterApp();
}
}
The JList API will show you two key methods:
public void setVisibleRowCount(int rowCount)
public void setPrototypeCellValue(E prototype)
So simply give your list an adequate row visible count and an adequately long enough prototype value, and then its enclosing JScrollPane's viewport will automatically size its viewport accordingly.
For example:
import java.awt.GridLayout;
import javax.swing.*;
public class JListExample extends JPanel {
private JList<String> list1 = new JList<>();
private JList<String> list2 = new JList<>();
public JListExample() {
list1.setVisibleRowCount(20);
list2.setVisibleRowCount(20);
list1.setPrototypeCellValue(String.format("%60s", ""));
list2.setPrototypeCellValue(String.format("%60s", ""));
setLayout(new GridLayout(1, 2));
add(new JScrollPane(list1));
add(new JScrollPane(list2));
}
private static void createAndShowGui() {
JListExample mainPanel = new JListExample();
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
Or better to avoid "magic" numbers:
public class JListExample extends JPanel {
private static final int LIST_ROW_COUNT = 20;
private static final int LIST_CHAR_WIDTH = 80;
private static final String LIST_PROTOTYPE = "%" + LIST_CHAR_WIDTH + "s";
private JList<String> list1 = new JList<>();
private JList<String> list2 = new JList<>();
public JListExample() {
list1.setVisibleRowCount(LIST_ROW_COUNT);
list2.setVisibleRowCount(LIST_ROW_COUNT);
list1.setPrototypeCellValue(String.format(LIST_PROTOTYPE, ""));
list2.setPrototypeCellValue(String.format(LIST_PROTOTYPE, ""));
Here, now you can see the lists better by my wrapping them and their JScrollPane in a JPanel that uses a TitledBorder:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class JListExample extends JPanel {
private static final int LIST_ROW_COUNT = 20;
private static final int LIST_CHAR_WIDTH = 80;
private static final String LIST_PROTOTYPE = "%" + LIST_CHAR_WIDTH + "s";
private JList<String> list1 = new JList<>();
private JList<String> list2 = new JList<>();
public JListExample() {
list1.setVisibleRowCount(LIST_ROW_COUNT);
list2.setVisibleRowCount(LIST_ROW_COUNT);
list1.setPrototypeCellValue(String.format(LIST_PROTOTYPE, ""));
list2.setPrototypeCellValue(String.format(LIST_PROTOTYPE, ""));
setLayout(new GridLayout(1, 2));
add(createListWrapper(list1, "JList 1"));
add(createListWrapper(list2, "JList 2"));
}
private JComponent createListWrapper(JList<String> list, String title) {
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel wrapperPanel = new JPanel(new BorderLayout());
wrapperPanel.add(scrollPane);
wrapperPanel.setBorder(BorderFactory.createTitledBorder(title));
return wrapperPanel;
}
private static void createAndShowGui() {
JListExample mainPanel = new JListExample();
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
Edit
As MadProgrammer states in comment:
I'd also be careful with prototypeCellValue, unless the value matches the expected length of your data, it could truncate your data when it's displayed, just need to be careful

Basic Multiply and Divide Java GUI

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.

Menubar not added in a java split pane

I have written a small test program which creates a split pane in which one of the pane's is a text area. I have added a meubar and menuitems to the pane but i donot see them in the gui that is created.
Could anyone pls point out what the wrong thing did i do over here in the below program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenuBar;
import java.util.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.IOException;
//SplitPaneDemo itself is not a visible component.
public class SplitPaneDemo extends JFrame
implements ActionListener {
private JTextArea ta;
private JMenuBar menuB;
private JMenu dbM;
private JMenuItem cnadb,bsmdb,cdmdb;
private JLabel picture;
private JSplitPane splitPane;
public SplitPaneDemo() {
ta = new JTextArea(); //textarea
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke )
{
int code = ke.getKeyCode();
int modifiers = ke.getModifiers();
if(code == KeyEvent.VK_ENTER && modifiers == KeyEvent.CTRL_MASK)
{
System.out.println("cmd in table:");
}
}
});
JScrollPane taPane = new JScrollPane(ta);
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
JScrollPane pictureScrollPane = new JScrollPane(picture);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
taPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(450);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 100);
taPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(900, 900));
menuB = new JMenuBar(); //menubar
dbM = new JMenu("DB"); //file menu
cnadb = new JMenuItem("CNA");
bsmdb = new JMenuItem("BSM");
cdmdb = new JMenuItem("CDM");
setJMenuBar(menuB);
menuB.add(dbM);
dbM.add(cnadb);
dbM.add(bsmdb);
dbM.add(cdmdb);
cnadb.addActionListener(this);
bsmdb.addActionListener(this);
cdmdb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
public void valueChanged(ListSelectionEvent e) {
}
public JSplitPane getSplitPane() {
return splitPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You add the JMenuBar in your SplitPaneDemo class, but when you actually call createAndShowGUI, you make a new JFrame and only add the SplitPane to it with the call to getSplitPane. This new frame has no knowledge of the menu bar.
If you are extending JFrame in SplitPaneDemo, why not use that to make the frame for your gui?

JComboBox with DefaultComboBoxModel doesn't allow to add or remove

This is my first post and I think I am doing it right.
I have a program that takes the user input from a AutoComplete jComboBox and then send's the input to be stored into a text file.(AutoComplete is done using the library glazedlists_java15/1.8.0).
After using the Autocomplet feature I had to set the jComboBox to DefaultComboBoxModel.
When the user presses the Enter key, the jComboBox should update the list with the new Item typed from the keyboard, so the user can see the last typed item in the jComboBox list.
This is done by removing all the items from the jComboBox and then inserting them again .
The problem is that before having the AutoComplete feature I could just say jComboBox1.removeAllItems(); but now because of the model I have to do it with model.removeAllElements();
public class Test {
final static DefaultComboBoxModel model = new DefaultComboBoxModel();
static JComboBox c = new JComboBox(model);
private static final long serialVersionUID = 1L;
private static JButton b = new JButton();
static JFrame f = new JFrame();
/**
* #param args
*/
public static void TestFrame() {
String[] a = {"hi1" , "hi2", "hi3", "hi4","hi5"};
AutoCompleteSupport support = AutoCompleteSupport.install(c,
GlazedLists.eventListOf(a));
JPanel test = new JPanel();
test.add(b);
test.add(c);
model.addElement(a);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.removeAllElements();
}
});
f.add(test);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(500,500);
}
The problem is that model.removeAllElements(); and model.addElement(s); is not working so I can not update the jComboBox. Can you please take your time and help me find a solution. Thanks!
Edit:
I don´t know where your problem is, this is totally working for me
final DefaultComboBoxModel model = new DefaultComboBoxModel();
JComboBox c = new JComboBox(model);
private static final long serialVersionUID = 1L;
private JButton b = new JButton();
public TestFrame() {
JPanel test = new JPanel();
test.add(b);
test.add(c);
model.addElement("hi");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.removeAllElements();
}
});
this.add(test);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(500,500);
}
maybe you don´t reach your keylistener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.swing.AutoCompleteSupport;
public class TestFrame
{
private static JComboBox c = new JComboBox();
private static JButton b = new JButton();
private static JFrame f = new JFrame();
private static String[] a = {"hi1", "hi2", "hi3", "hi4", "hi5"};
public static void TestFrame()
{
final EventList<String> items = GlazedLists.eventListOf(a);
AutoCompleteSupport.install(c, items);
JPanel test = new JPanel();
test.add(b);
test.add(c);
c.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
c = (JComboBox) e.getSource();
if (e.getActionCommand().equals("comboBoxEdited"))
{
items.clear();
}
}
});
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
items.clear();
}
});
f.add(test);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(500, 500);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
TestFrame();
}
});
}
}

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