Call JOptionPane repaint from internal panel - java

I have form with combo box. Depends of selected item at this combo box, some fields at form hides and some appears. But size of dialog not auto resized for repainted JPanel of the form. How to fix this?
Sscce.java:
import javax.swing.*;
public class Sscce extends JFrame {
Sscce() {
setTitle("Sscce");
// Sets the behavior for when the window is closed
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(new MainPanel());
pack();
}
public static void main(String[] args) {
Sscce application = new Sscce();
application.setVisible(true);
}
}
MainPanel.java:
import javax.swing.*;
public class MainPanel extends JPanel {
public MainPanel() {
final DeviceForm form = new DeviceForm();
JOptionPane.showConfirmDialog(null, form, "Add new device", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
}
}
DeviceForm.java:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class DeviceForm extends JPanel implements ActionListener {
private LinkedHashMap<String, JComponent> fields = new LinkedHashMap<String, JComponent>();
private HashMap<String, JPanel> borders = new HashMap<String, JPanel>();
public DeviceForm() {
String[] versions = {String.valueOf(1), String.valueOf(2),
String.valueOf(3)};
JComboBox versionList = new JComboBox(versions);
versionList.addActionListener(this);
versionList.setSelectedIndex(0);
fields.put("Version: ", versionList);
JTextField textField = new JTextField();
fields.put("Community: ", textField);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
for (Map.Entry<String, JComponent> entry : fields.entrySet()) {
JPanel borderPanel = new JPanel(new java.awt.BorderLayout());
borderPanel.setBorder(new javax.swing.border.TitledBorder(entry.getKey()));
borderPanel.add(entry.getValue(), java.awt.BorderLayout.CENTER);
add(borderPanel);
borders.put(entry.getKey(), borderPanel);
}
}
/**
* Repaint form fields for chosen version of SNMP
* #param e
*/
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int version = Integer.parseInt((String)cb.getSelectedItem());
if (version == 1) { // hide username and password, show community
JComponent field = borders.get("Username: ");
if (field != null)
remove(field);
field = borders.get("Password: ");
if (field != null)
remove(field);
field = borders.get("Community: ");
if (field != null)
add(field);
}
else if(version == 3) { // hide community, show username and password
JComponent field = borders.get("Community: ");
if (field != null)
remove(field);
field = borders.get("Username: ");
if (field == null)
addField("Username: ");
else
add(field);
field = borders.get("Password: ");
if (field == null)
addField("Password: ");
else
add(field);
}
validate();
repaint();
}
private void addField(String title) {
// Create field
JTextField textField = new JTextField();
fields.put(title, textField);
// Border created field
JPanel borderPanel = new JPanel(new java.awt.BorderLayout());
borderPanel.setBorder(new javax.swing.border.TitledBorder(title));
borderPanel.add(textField, java.awt.BorderLayout.CENTER);
add(borderPanel);
borders.put(title, borderPanel);
}
}

The solution is for you to use a CardLayout.
e.g.,
import java.awt.CardLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class Sscce2 extends JPanel {
private static final String COMMUNITY = "Community";
private static final String PASSWORD = "Password";
private static final String BLANK = "Blank";
private static final String[] VERSIONS = {COMMUNITY, PASSWORD, BLANK};
CardLayout cardLayout = new CardLayout();
JPanel cardHolderPanel = new JPanel(cardLayout);
JComboBox combobox = new JComboBox(VERSIONS);
private JPasswordField passwordField = new JPasswordField(15);
private JTextField communityTextField = new JTextField(15);
public Sscce2() {
cardHolderPanel.add(createCommunityPanel(), COMMUNITY);
cardHolderPanel.add(createPasswordPanel(), PASSWORD);
cardHolderPanel.add(new JLabel(), BLANK);
JPanel comboPanel = new JPanel();
comboPanel.setLayout(new BoxLayout(comboPanel, BoxLayout.PAGE_AXIS));
comboPanel.setBorder(BorderFactory.createTitledBorder("Version:"));
comboPanel.add(combobox);
setLayout(new GridLayout(0, 1));
add(comboPanel);
add(cardHolderPanel);
combobox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String selection = combobox.getSelectedItem().toString();
cardLayout.show(cardHolderPanel, selection);
}
});
}
public String getCommunityText() {
return communityTextField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
private JPanel createCommunityPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createTitledBorder(COMMUNITY));
panel.add(communityTextField);
return panel;
}
private JPanel createPasswordPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.setBorder(BorderFactory.createTitledBorder(PASSWORD));
panel.add(passwordField);
return panel;
}
private static void createAndShowGui() {
Sscce2 sscce2 = new Sscce2();
JOptionPane.showMessageDialog(null, sscce2, "SSCCE 2", JOptionPane.PLAIN_MESSAGE);
System.out.println("Community text: " + sscce2.getCommunityText());
System.out.println("Password: " + new String(sscce2.getPassword())); // *** never do this!
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Related

In JTabbedPane, I have two panels where same textfield and label are not displayed when written

I wanted to display same textfield and label in both the panels that are added to JTabbedPane but one of panel is displaying the textfield and label and the other is not, when added the same textfield and label for both the panels.
You can only display a component in one container. Better to have your JPanels share the same model, which for the JTextField is its Document, and for the JLabel -- well its text (not really a model that you can extract, so you'll have to change both yourself).
A bit overconvoluted example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.EventListenerList;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
#SuppressWarnings("serial")
public class SharedModels extends JPanel {
private static final int TABS = 10;
private JTabbedPane tabbedPane = new JTabbedPane();
private JTextField labelText = new JTextField(10);
private MyModel myModel = new MyModel();
public SharedModels() {
for (int i = 0; i < TABS; i++) {
MyPanel myPanel = new MyPanel(myModel);
String text = "tab: " + (i + 1);
tabbedPane.addTab(text, myPanel);
}
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Text for JLabel:"));
topPanel.add(labelText);
labelText.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
setLabelText(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
setLabelText(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
setLabelText(e);
}
private void setLabelText(DocumentEvent e) {
Document doc = e.getDocument();
int length = doc.getLength();
try {
String text = doc.getText(0, length);
myModel.setLabelText(text);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(tabbedPane, BorderLayout.CENTER);
add(new MyPanel(myModel), BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
SharedModels mainPanel = new SharedModels();
JFrame frame = new JFrame("SharedModels");
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 MyModel {
private Document document = new PlainDocument();
private String labelText = "";
private EventListenerList eventListenerList = new EventListenerList();
private ChangeEvent changeEvent = null;
public void addChangeListener(ChangeListener l) {
eventListenerList.add(ChangeListener.class, l);
}
public void removeChangeListener(ChangeListener l) {
eventListenerList.remove(ChangeListener.class, l);
}
public String getLabelText() {
return labelText;
}
public void setLabelText(String labelText) {
this.labelText = labelText;
fireChangeListeners();
}
protected void fireChangeListeners() {
Object[] listeners = eventListenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
public Document getDocument() {
return document;
}
}
#SuppressWarnings("serial")
class MyPanel extends JPanel {
private JLabel label = new JLabel("");
private JTextField textField = new JTextField(10);
public MyPanel(MyModel myModel) {
textField.setDocument(myModel.getDocument());
myModel.addChangeListener(ce -> {
label.setText(myModel.getLabelText());
});
add(new JLabel("Label text:"));
add(label);
add(textField);
setPreferredSize(new Dimension(400, 100));
}
}

Reading text file from a GUI

I have a GUI that verifies a username and password. The other part of the assignment is to read from a file that contains a username and a password and checks to see if it matches what the user put in the text field. If it does match then it will hide the Login page and another page will appear with a "Welcome" message. I have zero experience with text files, where do I put that block of code? I assume it would go in the ActionListener method and not the main method but i'm just lost. I just need a little push in the right direction. Here is what I have so far. Any help would be greatly appreciated. Thanks!
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}
import javax.swing.*;
import java.awt.*;
/**
*/
public class PassWordFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new PassWordFrame();
frame.setTitle("Password Verification");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
First of all you initialize the listener (listener = new ClickListener()) after the call to #createComponents() method so this means you will add a null listener to the login button. So your constructor should look like this:
public PassWordFrame() {
listener = new ClickListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
Then, because you want to change the GUI with a welcome message, you should use a SwingWorker, a class designed to perform GUI-interaction tasks in a background thread. In the javadoc you can find nice examples, but here is also a good tutorial: Worker Threads and SwingWorker.
Below i write you only the listener implementation (using a swing worker):
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
new SwingWorker<Boolean, Void>() {
#Override
protected Boolean doInBackground() throws Exception {
String inputFileName = ("users.txt");
File userFile = new File(inputFileName);
BufferedReader reader = new BufferedReader(new FileReader(userFile));
String user;
String pass;
try {
user = reader.readLine();
pass = reader.readLine();
}
catch (IOException e) {
//
// in case something is wrong with the file or his contents
// consider login failed
user = null;
pass = null;
//
// log the exception
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// ignore, nothing to do any more
}
}
if (usertext.getText().equals(user) && passtext.getText().equals(pass)) {
return true;
} else {
return false;
}
}
#Override
protected void done() {
boolean match;
try {
match = get();
}
//
// this is a learning example so
// mark as not matching
// and print exception to the standard error stream
catch (InterruptedException | ExecutionException e) {
match = false;
e.printStackTrace();
}
if (match) {
// show another page with a "Welcome" message
}
}
}.execute();
}
}
Another tip: don't add components to a JFrame, so replace this:
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
with:
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.WEST);
contentPane.add(panel3, BorderLayout.CENTER);
contentPane.add(panel4, BorderLayout.SOUTH);
setContentPane(contentPane);
assume there is a textfile named password.txt in g driver and it contain usename and password separate by # symbol.
like following
password#123
example code
package homework;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 300;
private JLabel fileRead;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
//String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
String info = ReadFile();
System.out.println(info);
String[] split = info.split("#");
String uname=split[0];
String pass =split[1];
if(usertext.getText().equals(uname) && passtext.getText().equals(pass)){
instruct.setText("access granted");
}else{
instruct.setText("access denided");
}
}
});
}
private static String ReadFile(){
String line=null;
String text="";
try{
FileReader filereader=new FileReader(new File("G:\\password.txt"));
//FileReader filereader=new FileReader(new File(path));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line;
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
panel1.setBackground(blue);
panel2.setBackground(blue);
panel3.setBackground(blue);
panel4.setBackground(blue);
panel1.add(instruct);
panel2.add(username);
panel2.add(usertext);
panel3.add(password);
panel3.add(passtext);
panel4.add(login);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.WEST);
add(panel3, BorderLayout.CENTER);
add(panel4, BorderLayout.SOUTH);
pack();
}
}

How do I add mnemonics in java swing?

So I have a greeting program with 3 JTextfields and 3 JLabels next to them and I want to add mnemonics, which I believe is the little underline underneath one of the letters in the JLabel next to the JTextField. When the user presses Alt+underlined key, then the cursor will go to the JTextfield next to it. Here is my code so that just shows the simple greeting without mnemonics
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GreetingApp extends JFrame {
private static final long serialVersionUID = 1L;
private final JTextField firstNameField,middleNameField,lastNameField;
private final JButton greetingButton;
public GreetingApp() {
super("Greetings");
this.firstNameField = new JTextField(8);
this.middleNameField = new JTextField(8);
this.lastNameField = new JTextField(8);
this.greetingButton = new JButton("Get Greeting");
greetingButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent ae){
showGreeting();
}
});
final Container mainPanel = getContentPane();
mainPanel.setLayout(new BorderLayout());
final JPanel inputPanel = new JPanel();
final JPanel buttonPanel = new JPanel();
inputPanel.setLayout(new GridLayout(3,3,3,5));
buttonPanel.setLayout(new FlowLayout());
JSeparator sep = new JSeparator();
inputPanel.add(new JLabel("First Name: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(firstNameField);
inputPanel.add(new JLabel("MI: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(middleNameField);
inputPanel.add(new JLabel("Last Name: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(lastNameField);
mainPanel.add(inputPanel,BorderLayout.PAGE_START);
//buttonPanel.add(sep,BorderLayout.PAGE_START);
mainPanel.add(sep,BorderLayout.CENTER);
buttonPanel.add(greetingButton);
mainPanel.add(buttonPanel,BorderLayout.PAGE_END);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private String getFullName() throws IllegalStateException{
if(firstNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("First name cannot be blank");
}
if(middleNameField.getText().trim().length() > 1){
throw new IllegalArgumentException("Middle intial cannot be greater than 1 letter");
}
if(lastNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("Last name cannot be blank");
}
if(middleNameField.getText().trim().length() ==0){
return "Greetings, "+this.firstNameField.getText()+" "+ this.middleNameField.getText() +this.lastNameField.getText()+"!";
}
return "Greetings, "+this.firstNameField.getText()+" "+ this.middleNameField.getText()+"."+this.lastNameField.getText()+"!";
}
private void showGreeting(){
try{
String message = getFullName();
JOptionPane.showMessageDialog(this, message);
}catch(final IllegalArgumentException iae){
JOptionPane.showMessageDialog(this,
iae.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
try{
for(LookAndFeelInfo info:UIManager.getInstalledLookAndFeels()){
if("Nimbus".equals(info.getName())){
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}catch(Exception e){
e.getStackTrace();
}
}
}
If your JLabel is called label and your JTextField is called textField:
label.setDisplayedMnemonic(KeyEvent.VK_N); //replace .VK_N with the appropriate key
will place the mnemonic on the label, and:
label.setLabelFor(textField);
will associate that label (and its mnemonic) with the appropriate text field

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

JProgressbar width using Grid/FlowLayout

I'm working on a downloader which looks like this at the moment:
The JFrame uses a BorderLayout.
In the NORTH, I have a JPanel(FlowLayout). In the SOUTH there is also a JPanel(FlowLayout), in the WEST I just have a JTextArea (in a JScrollPane). This is all shown correctly. However, in the EAST I currently have a JPanel(GridLayout(10, 1)).
I want to show up to 10 JProgressBars in the EAST section which are added and removed from the panel dynamically. The problem is, I can not get them to look like I want to them to look: I want the JProgressBars' width to fill up the entire EAST section because 1) This gives the app a more symmetrical look and 2) The ProgressBars may contain long strings that don't fit at the moment. I've tried putting the JPanel that contains the GridLayout(10, 1) in a flowlayout and then put that flowlayout in the EAST section, but that didn't work either.
My code (SSCCE) is currently as follows:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
new DownloadFrame();
}
private static class DownloadFrame extends JFrame {
private JButton downloadButton;
private JTextField threadIdTextField;
private JTextArea downloadStatusTextArea;
private JScrollPane scrollPane;
private JTextField downloadLocationTextField;
private JButton downloadLocationButton;
private JPanel North;
private JPanel South;
private JPanel ProgressBarPanel;
private Map<String, JProgressBar> progressBarMap;
public DownloadFrame() {
InitComponents();
InitLayout();
AddComponents();
AddActionListeners();
setVisible(true);
setSize(700, 300);
}
private void InitComponents() {
downloadButton = new JButton("Dowload");
threadIdTextField = new JTextField(6);
downloadStatusTextArea = new JTextArea(10, 30);
scrollPane = new JScrollPane(downloadStatusTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
downloadLocationTextField = new JTextField(40);
downloadLocationButton = new JButton("...");
North = new JPanel();
South = new JPanel();
ProgressBarPanel = new JPanel();
progressBarMap = new HashMap<String, JProgressBar>();
}
private void InitLayout() {
North.setLayout(new FlowLayout());
South.setLayout(new FlowLayout());
ProgressBarPanel.setLayout(new GridLayout(10, 1));
}
private void AddComponents() {
North.add(threadIdTextField);
North.add(downloadButton);
add(North, BorderLayout.NORTH);
add(ProgressBarPanel, BorderLayout.EAST);
South.add(downloadLocationTextField);
South.add(downloadLocationButton);
add(South, BorderLayout.SOUTH);
add(scrollPane, BorderLayout.WEST);
}
private void AddActionListeners() {
downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addNewProgessBar(threadIdTextField.getText());
}
});
}
public void addNewProgessBar(String threadId) {
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBarMap.put(threadId, progressBar);
drawProgessBars();
}
void drawProgessBars() {
ProgressBarPanel.removeAll();
for (JProgressBar progressBar : progressBarMap.values()) {
ProgressBarPanel.add(progressBar);
}
validate();
repaint();
}
}
}
Thanks in advance.
EDIT
Easiest solution: change
add(ProgressBarPanel, BorderLayout.EAST);
to
add(ProgressBarPanel, BorderLayout.CENTER);
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
new DownloadFrame();
}
private static class DownloadFrame extends JFrame {
private JButton downloadButton;
private JTextField threadIdTextField;
private JTextArea downloadStatusTextArea;
private JScrollPane scrollPane;
private JTextField downloadLocationTextField;
private JButton downloadLocationButton;
private JPanel North;
private JPanel South;
private JPanel ProgressBarPanel;
private Map<String, JProgressBar> progressBarMap;
public DownloadFrame() {
InitComponents();
AddComponents();
AddActionListeners();
pack();
setVisible(true);
//setSize(700, 300);
}
private void InitComponents() {
setLayout(new BorderLayout());
downloadButton = new JButton("Dowload");
threadIdTextField = new JTextField(6);
downloadStatusTextArea = new JTextArea(10, 30);
scrollPane = new JScrollPane(downloadStatusTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
downloadLocationTextField = new JTextField(40);
downloadLocationButton = new JButton("...");
North = new JPanel(new FlowLayout());
South = new JPanel(new FlowLayout());
ProgressBarPanel = new JPanel(new GridLayout(0, 1));
ProgressBarPanel.setBorder(new LineBorder(Color.black));
ProgressBarPanel.setPreferredSize(new Dimension(300,20));
progressBarMap = new HashMap<String, JProgressBar>();
}
private void AddComponents() {
North.add(threadIdTextField);
North.add(downloadButton);
add(North, BorderLayout.NORTH);
add(ProgressBarPanel, BorderLayout.EAST);
South.add(downloadLocationTextField);
South.add(downloadLocationButton);
add(South, BorderLayout.SOUTH);
add(scrollPane, BorderLayout.WEST);
}
private void AddActionListeners() {
downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addNewProgessBar(threadIdTextField.getText());
}
});
}
public void addNewProgessBar(String threadId) {
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBarMap.put(threadId, progressBar);
drawProgessBars();
}
void drawProgessBars() {
ProgressBarPanel.removeAll();
for (JProgressBar progressBar : progressBarMap.values()) {
ProgressBarPanel.add(progressBar);
}
validate();
repaint();
}
}
}
well. that possible, but in your example CENTER area occupated some Rectangle, its hard to reduce/remove CENTER area to the zero Size
to the North JPanel (BorderLayout) place another JPanel and put it to the EAST (with LayoutManager would be GridLayout(1,2,10,10)) and put here two JComponents JTextField - threadIdTextField and JButton - downloadButton, there you are needed setPreferredSize 1) for JComponents (correct way) or 2) for whole JPanel (possible way too)
JScrollPane with JTextArea must be placed to the CENTER area
JPanel with JProgressBars place to EAST, but again set same PreferredSize as for JPanel with JTextField and JButton from the NORTH
SOUTH JPanel remains without changes
Please post a compilable runnable small program for the quickest best help, an SSCCE.
Suggestions include using GridLayout(0, 1) (variable number of rows, one column), or display the JProgressBars in a JList that uses a custom renderer that extends JProgressBar.
Edit 1:
I know that Andrew has already posted the accepted answer (and 1+ for an excellent answer), but I just wanted to demonstrate that this can be done readily with a JList, something like so:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.Random;
import javax.swing.*;
public class EastProgressList extends JPanel {
private DefaultListModel myListModel = new DefaultListModel();
private JList myList = new JList(myListModel);
private JTextField downloadUrlField = new JTextField(10);
public EastProgressList() {
JButton downLoadBtn = new JButton("Download");
downLoadBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
downloadAction();
}
});
JPanel northPanel = new JPanel();
northPanel.add(new JLabel("File to Download:"));
northPanel.add(downloadUrlField);
northPanel.add(Box.createHorizontalStrut(15));
northPanel.add(downLoadBtn);
myList.setCellRenderer(new ProgressBarCellRenderer());
JScrollPane eastSPane = new JScrollPane(myList);
eastSPane.setPreferredSize(new Dimension(200, 100));
setLayout(new BorderLayout());
add(new JScrollPane(new JTextArea(20, 30)), BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
add(eastSPane, BorderLayout.EAST);
}
private void downloadAction() {
String downloadUrl = downloadUrlField.getText();
final MyData myData = new MyData(downloadUrl);
myListModel.addElement(myData);
myData.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(MyData.VALUE)) {
myList.repaint();
if (myData.getValue() >= 100) {
myListModel.removeElement(myData);
}
}
}
});
}
private class ProgressBarCellRenderer extends JProgressBar implements ListCellRenderer {
protected ProgressBarCellRenderer() {
setBorder(BorderFactory.createLineBorder(Color.blue));
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
//setText(value.toString());
MyData myData = (MyData)value;
setValue(myData.getValue());
setString(myData.getText());
setStringPainted(true);
return this;
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("EastProgressList");
frame.getContentPane().add(new EastProgressList());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyData {
public static final int TIMER_DELAY = 300;
public static final String VALUE = "value";
protected static final int MAX_DELTA_VALUE = 5;
private String text;
private int value = 0;
private Random random = new Random();
private PropertyChangeSupport pcSupport = new PropertyChangeSupport(this);
public MyData(String text) {
this.text = text;
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int deltaValue = random.nextInt(MAX_DELTA_VALUE);
int newValue = value + deltaValue;
if (newValue >= 100) {
newValue = 100;
((Timer)e.getSource()).stop();
}
setValue(newValue);
}
}).start();
}
public String getText() {
return text;
}
public int getValue() {
return value;
}
public void setValue(int value) {
int oldValue = this.value;
this.value = value;
PropertyChangeEvent pcEvent = new PropertyChangeEvent(this, VALUE, oldValue, value);
pcSupport.firePropertyChange(pcEvent);
}
public void addPropertyChangeListener(PropertyChangeListener pcListener) {
pcSupport.addPropertyChangeListener(pcListener);
}
}
This results in a GUI looking like so:

Categories

Resources