I am trying to open a new JFrame window with a button click event. There is lots of info on this site but nothing that helps me because I think it is not so much the code I have, but the order it is executed (however I am uncertain).
This is the code for the frame holding the button that I want to initiate the event:
package messing with swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
public ReportGUI(){
reportInterface();
allReportsBtn();
examinnerFileRead();
courseFileRead();
comboBoxes();
}
private void examinnerFileRead(){
try{
Scanner scan = new Scanner(new File("Examiner.txt"));
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void courseFileRead(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
courseList.add(scan.nextLine());
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame AllDataGUI = new JFrame();
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = list.toArray(new String[list.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
add(panel, BorderLayout.LINE_START);
}
If you don't want to delve into the above code, the button ActionListener is here:
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame ViewCourseGUI = new JFrame();
new ViewCourseGUI();
}
});
This is the code in the class holding the JFrame I want to open:
package messing with swing;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class ViewCourseGUI extends JFrame{
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Courses taught by this examiner");
private JTextArea textArea = new JTextArea();
public void ViewCoursesGUI(){
panels();
}
private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
Could someone please point me in the right direction?
As pointed out by PM 77-3
I had:
public void ViewCoursesGUI(){
panels();
}
When I should have had:
public ViewCourseGUI(){
panels();
}
A Combination of syntax and spelling errors.
Set the visibility of the JFrame you want to open, to true in the actionListener:
ViewCourseGUI viewCourseGUI = new ViewCourseGUI();
viewCourseGUI.setVisible(true);
This will open the new JFrame window once you click the button.
Let ReportGUI implement ActionListener. Then you will implement actionPerformed for the button click. On button click, create the second frame (if it doesn't exist). Finally, set the second frame visible (if it is currently not visible):
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ReportGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 8679886300517958494L;
private JButton button;
private ViewCourseGUI frame2 = null;
public ReportGUI() {
//frame1 stuff
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setLayout(new FlowLayout());
//create button
button = new JButton("Open other frame");
button.addActionListener(this);
add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReportGUI frame = new ReportGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
if (frame2 == null)
frame2 = new ViewCourseGUI();
if (!frame2.isVisible())
frame2.setVisible(true);
}
}
}
This is a simple example. You'll have to add the rest of your code here.
Related
I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}
I'm writing a GUI in java. I have a JXTable in which I currently only have static data, but I want allow the user to input data by using a template panel that I have created.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
public class Template_StackOverflowExample extends JPanel{
private JPanel diagPanel = new dialogTemplate();
Object[] columnIdentifiers = {
"id",
"imei",
};
Object[][] data = {
{"1", "123"},
{"2", "123"},
{"3", "123"}
};
private JDialog dialog;
private static DefaultTableModel model;
public Template_StackOverflowExample(){
setLayout(new BorderLayout());
JPanel pane = new JPanel(new BorderLayout());
JButton addRow = new JButton("Add Row");
addRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Add Row");
}
});
JButton editRow = new JButton("Edit Row");
editRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openRowPane("Edit Row");
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1));
TitledBorder buttonBorder = new TitledBorder("Buttons");
buttonPane.setBorder(buttonBorder);
buttonPane.add(addRow);
buttonPane.add(editRow);
model = new DefaultTableModel();
model.setColumnIdentifiers(columnIdentifiers);
JTable table = new JTable(model);
for(int i = 0; i < data.length; i++){
model.insertRow(i, data[i]);
}
JScrollPane scrollPane = new JScrollPane(table);
pane.add(buttonPane, BorderLayout.LINE_END);
pane.add(scrollPane, BorderLayout.CENTER);
add(pane, BorderLayout.CENTER);
}
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null){
dialog = new JDialog(win, name, ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true);
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("MCVE");
Template_StackOverflowExample mainPanel = new Template_StackOverflowExample();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class dialogTemplate extends JPanel{
private JComponent[] content;
private String[] labelHeaders = {
"ID:",
"IMEI:",
};
public dialogTemplate(){
JPanel diagTemplate = new JPanel();
diagTemplate.setLayout(new BorderLayout());
JPanel rowContent = new JPanel(new GridLayout(0, 2));
JLabel idLabel = null;
JLabel imeiLabel = null;
JLabel[] labels = {
idLabel,
imeiLabel,
};
JTextField idTextField = new JTextField(20);
JTextField imeiTextField = new JTextField(20);
content = new JComponent[] {
idTextField,
imeiTextField,
};
for(int i = 0; i < labels.length; i++){
labels[i] = new JLabel(labelHeaders[i]);
rowContent.add(labels[i]);
rowContent.add(content[i]);
labels[i].setLabelFor(content[i]);
}
JButton save = new JButton("Save");
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeWindow();
}
});
JPanel buttonPane = new JPanel(new GridLayout(0, 1, 5, 5));
buttonPane.add(save);
buttonPane.add(cancel);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
diagTemplate.add(buttonPane, BorderLayout.PAGE_END);
diagTemplate.add(rowContent, BorderLayout.CENTER);
add(diagTemplate);
}
public void closeWindow(){
Window win = SwingUtilities.getWindowAncestor(this);
if(win != null) {
win.dispose();
}
}
}
As you might see both of the buttons in the pane creates the dialog that is created first ("Add Row" or "Edit Row"). I want them to create different dialogs so that the editing of data doesn't conflict with the addition of data.
Thanks in advance.
Assign a different dialog-creating method to each button so you can open two dialogs:
public void openRowPane(String name){
if(dialog == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog = new JDialog(win, name, ModalityType.MODELESS);
dialog.getContentPane().add(diagPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
dialog.setVisible(true);
}
public void openRowPane2(String name){
if(dialog2 == null){
Window win = SwingUtilities.getWindowAncestor(this);
//change modality
dialog2 = new JDialog(win, name, ModalityType.MODELESS);
dialog2.getContentPane().add(diagPanel2);
dialog2.pack();
dialog2.setLocationRelativeTo(null);
}
dialog2.setVisible(true);
}
How do I make my textfields and button centered?
Edit: Updated my post with SSCE. Hopefully that helps.
By the way, I want the left image to look like the right.
package pkg;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel();
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.add(username);
panel.add(password);
panel.add(login);
panel.add(status);
game.add(logout);
frame.add(panel);
frame.setSize(806, 553);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
try {
Client.socketOut.writeUTF("logout");
Client.socketOut.writeUTF(Client.username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
What I want it to look like:
I've tried to use many different layout styles but I can't seem to make it work...
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.*;
public class Game {
private static JPanel panel = new JPanel();
public static JTextField username = new JTextField(20);
public static JPasswordField password = new JPasswordField(20);
JButton login = new JButton("Login");
JLabel status = new JLabel();
private static JPanel game = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JButton logout = new JButton("Logout");
private static JFrame frame = new JFrame("RuneShadows");
public Game() {
panel.setLayout(new GridLayout(0,1,15,15));
panel.setBorder(new EmptyBorder(50,100,50,100));
panel.add(username);
panel.add(password);
panel.add(status);
JPanel logoutConstrain = new JPanel(new FlowLayout(FlowLayout.CENTER));
logoutConstrain.add(logout);
panel.add(logoutConstrain);
frame.setLayout(new GridBagLayout());
frame.add(panel);
//frame.setSize(806, 553); // forget this nonsense, instead..
frame.pack(); // best!
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public void loadGame() {
frame.remove(panel);
frame.revalidate();
frame.add(game);
frame.revalidate();
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(game);
frame.revalidate();
frame.add(panel);
frame.revalidate();
}
});
}
}
Note: I've searched all over the web (this site and others) and cannot answer this myself.
Ok guys. I am a new Java programmer, and we just got done covering tabbed panes. This is the state in which I turned in my assignment: it doesn't work, and I can't figure out why. I've changed so much crap around, I can't keep it straight in my head anymore, but I know it's probably something incredibly simple.
I apologize for the length of the code, but I'm trying to give you the entirety of my code so you can tell me where I jacked it up.
Thanks in advance. -- Also, I'm aware there are other Warnings (i.e. unused imports), but I'm not worried about those. And, this will not affect my grade (as I said, already submitted), but I want to know wtf I did wrong!
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.awt.Color;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JComponent;
public class TabbedPane1 extends JPanel
{
public TabbedPane1()
{
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
}
public static void main(String[] args)
{
JFrame myFrame = new JFrame("Tabbed Programs");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.add(new TabbedPane1(), BorderLayout.CENTER);
myFrame.pack();
myFrame.setVisible(true);
}
class DayGui extends JPanel
{
private JPanel mainFrame;
private JButton cmdGood;
private JButton cmdBad;
public DayGui()
{
mainFrame = new JPanel();
cmdGood = new JButton("Good");
cmdBad = new JButton("Bad");
Container myContainer = mainFrame;
myContainer.setLayout(new FlowLayout());
myContainer.add(cmdGood);
myContainer.add(cmdBad);
cmdGood.setMnemonic('G');
cmdBad.setMnemonic('B');
mainFrame.setSize(300, 100);
myContainer.setBackground(Color.blue);
cmdGood.setBackground(Color.cyan);
cmdBad.setBackground(Color.cyan);
/*mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
ButtonsHandler bhandler = new ButtonsHandler();
cmdGood.addActionListener(bhandler);
cmdBad.addActionListener(bhandler);
//mainFrame.setVisible(true);
}
class ButtonsHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == cmdGood)
JOptionPane.showMessageDialog(null, "Today is a good day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
if(e.getSource() == cmdBad)
JOptionPane.showMessageDialog(null, "Today is a bad day!",
"Event Handler Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
class OfficeAreaCalculator extends JPanel
{
private JPanel mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator()
{
mainFrame = new JPanel();
exitButton = new JButton("Exit");
calculateButton = new JButton("Calculate");
lengthField = new JTextField(5);
widthField = new JTextField(5);
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
areaField = new JTextField(5);
areaField.setEditable(false);
Container c = mainFrame;
c.setLayout(new FlowLayout());
c.setBackground(Color.green);
c.add(lengthLabel);
c.add(lengthField);
c.add(widthLabel);
c.add(widthField);
c.add(areaLabel);
c.add(areaField);
c.add(calculateButton);
c.add(exitButton);
calculateButton.setMnemonic('C');
exitButton.setMnemonic('x');
mainFrame.setSize(260, 150);
/*mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
//mainFrame.setVisible(true);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(",###.##");
double width, length, area;
String instring;
instring = lengthField.getText();
if(instring.equals(""))
{
instring = ("0");
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if(instring.equals(""))
{
instring = ("0");
widthField.setText("0");
}
width = Double.parseDouble(instring);
area = length * width;
areaField.setText(num.format(area));
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if(e.getSource() == lengthField || e.getSource() == widthField)
{
areaField.setText("");
}
else if(e.getSource() == areaField)
{
calculateButton.requestFocus();
}
}
public void focusLost(FocusEvent e)
{
if(e.getSource() == widthField)
{
calculateButton.requestFocus();
}
}
}
}
}
You added your JTabbedPane on JPanel.
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
Since JPanel has a FlowLayout as a default, you have this issue. Set layout of your JPanelto BorderLayout and problem will be solved.
setLayout(new BorderLayout()); //Here
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
add(tabbedPane);
EDIT:
Also, avoid extending your classes with swing components if you don't want to override methods or define new ones. Prefer composition instead of that. I had that same bad habbit.
For example, instead of extending tour TabbedPane1 class with JPanel, it would be better to just create a method which returns customized JTabbedPane. Something like this:
public JTabbedPane getTabbedPane() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("DayGui", new DayGui());
tabbedPane.addTab("OfficeCalc", new OfficeAreaCalculator());
return tabbedPane;
}
To call it:
myFrame.add(new TabbedPane1().getTabbedPane(), BorderLayout.CENTER);
This way your class will be "opened" for inheritance.
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