I'm having some trouble with the GUI is used to make the GUI and a button but now it makes only the GUI. Plus I can't figure out how to make the auto clicker run with the GUI itself.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Clicker {
public JTextField ClickSpd;
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame {
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame() {
super("AutoClicker Version 1.0.8");
setLayout(new FlowLayout());
setSize(300, 100);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter Clicking Speed (Milliseconds)"));
ClickSpd = new JTextField(20);
panel.add(ClickSpd);
add(panel, BorderLayout.CENTER);
}
public JTextField ClickSpd;
class ButtonPanel extends JPanel implements ActionListener {
private Component frame;
public ButtonPanel() {
final JButton b2 = new JButton("Start");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("Start");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonFrame bf = new ButtonFrame();
if ("Start".equals(e.getActionCommand())) {
int rate = 0;
while (rate == 0) {
try {
System.out.println("Speed of the autoclicker (in milliseconds): ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
rate = Integer.parseInt(in.readLine());
if (rate < 1) {
rate = 0;
System.out.println("Must be at least 1.");
}
} catch (NumberFormatException ex) {
System.out.println("Error - please try again.");
}
} catch (IOException e1) {}
}
try {
Robot robot = new Robot();
while (true) {
try {
Thread.sleep(rate);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.keyRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {}
}
} catch (AWTException e1) {}
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not Supported yet.");
}
}
}
A BorderLayout can have as many as 5 components, one per layout constraint (e.g. BorderLayout.PAGE_START).
That code adds two components to the BorderLayout.CENTER area.
Other tips:
It's always best to ask one specific question, given this is a Q&A site.
Don't extend GUI components unnecessarily. In this case you should be simply using an instance of a JFrame and JPanel.
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use them consistently.
Related
I need a running order of pages 1-5 pages. I am using the card layout to navigate between each page after entering data on each page. The navigation to the next page works via an Action Listener on each text field.
My question is how do I pass the input from each card/page to the next? I can System.out.println each TextFeilds data. But I can't grab this information in the next card/action listener. The reason I need this to happen is I'd like to compare the strings of each page and also display a label of page 1's input on page/card2.
I apologize in advance for the massive block of code... Most of you will recognise most of this code anyway as it's copied from the CardLayout sample java code. I have just added two cards just now until I get the basics of passing variables back and fourth.
All help is appreciated even a small push the the right direction.
import java.awt.*;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Scanner;
import javax.swing.*;
public class CardLayoutDemo implements ItemListener {
JPanel cards; //a panel that uses CardLayout
final static String TEXTPANEL = "Card1 with text";
final static String TEXTPANEL2 = "Card with JTextField";
public void addComponentToPane(Container pane) {
//Put the JComboBox in a JPanel to get a nicer look.
JPanel comboBoxPane = new JPanel(); //use FlowLayout
String comboBoxItems[] = { TEXTPANEL, TEXTPANEL2};
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
//Create the "cards".
JPanel card1 = new JPanel();
JTextField jtf=new JTextField("", 40);
jtf.setSize(40, 10);
card1.add(jtf);
JLabel lab1 = new JLabel("Page1 Text", JLabel.LEFT);
card1.add(lab1 = new JLabel("Page1"));
JPanel card2 = new JPanel();
JTextField jtf2=new JTextField("", 40);
jtf2.setSize(40, 10);
card2.add(jtf2);
JLabel lab2 = new JLabel("Page2 Text", JLabel.LEFT);
card2.add(lab2 = new JLabel("Page2 "));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, TEXTPANEL);
cards.add(card2, TEXTPANEL2);
pane.add(cards, BorderLayout.CENTER);
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String getText1 = jtf.getText();
System.out.println("PAGE1 ");
System.out.println(getText1);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, TEXTPANEL2);
jtf2.requestFocus();
jtf2.requestFocusInWindow();
}
//JOptionPane.showMessageDialog(null,"Action Listener is working");
});
//PAGE2
jtf2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String getText2 = jtf2.getText();
System.out.println("PAGE2 ");
System.out.println(getText2);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, TEXTPANEL);
jtf.requestFocus();
jtf.requestFocusInWindow();
jtf.setText("");
}
});
}//ADD COMPONENT TO PANE
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
// String getLoginUser1 = jtf.getText();
//System.out.println(getLoginUser1);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 300));
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the content pane.
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Here is another view on the problem. You could create some kind of cards manager and hold all required info inside of it. Here is an example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class CardLayoutDemo implements ItemListener {
private static class QuizManager {
final java.util.List<String> quizData = new ArrayList<>();
final java.util.List<JPanel> cards = new ArrayList<>();
final JPanel rootView;
public QuizManager(JPanel root){
rootView = root;
}
private JPanel createQuizPanel(String pageText, final int index) {
JPanel card = new JPanel();
JTextField jtf=new JTextField("", 40);
jtf.setSize(40, 10);
JLabel prev = new JLabel("", JLabel.LEFT);
card.add(prev);
card.add(jtf);
card.add(new JLabel(pageText, JLabel.LEFT));
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
QuizManager.this.onCardSubmited(card, index, jtf.getText());
}
});
card.addComponentListener(new ComponentAdapter() {
#Override
public void componentShown(ComponentEvent e) {
super.componentShown(e);
jtf.requestFocus();
jtf.requestFocusInWindow();
String text = QuizManager.this.getPrevStringFor(index);
if (text != null) {
prev.setText(text);
}
}
});
return card;
}
private String getPrevStringFor(int index) {
if (index == 0) return null;
return quizData.get(index-1);
}
private String buildPanelName(int index) {
return String.format("card-%d", index);
}
public QuizManager addCard(String title) {
int index = cards.size();
quizData.add(null);//not set yet, just allocating
JPanel card = createQuizPanel(title, index);
cards.add(card);//this array looks like redundant
rootView.add(card, buildPanelName(index));
return this;
}
private void showCard(int index) {
CardLayout cl = (CardLayout) (rootView.getLayout());
cl.show(rootView, buildPanelName(index));
}
public void show() {
showCard(0);
}
public void onCardSubmited(JPanel card, int cardIndex, String text) {
System.out.println("page " + cardIndex);
System.out.println("text : " + text);
quizData.set(cardIndex, text);
if (cardIndex < cards.size() - 1) {
showCard(cardIndex + 1);
} else {
System.out.println("WE FINISHED");
//add finalazing code here
}
}
}
JPanel cardsRoot;
public void addComponentToPane(Container pane) {
cardsRoot = new JPanel(new CardLayout());
QuizManager manager = new QuizManager(cardsRoot)
.addCard("First page")
.addCard("Second page")
.addCard("Third card")
.addCard("Forth card");
pane.add(cardsRoot, BorderLayout.CENTER);
manager.show();
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cardsRoot.getLayout());
cl.show(cardsRoot, (String)evt.getItem());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 300));
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the content pane.
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Take a look how easy would be to create many of cards.
You've got the variable declaration of key components buried within the addComponentToPane(...) method, limiting their scope to this method only, preventing you from getting the information you need. While the canonical solution for this sort of problem is to use an model-view-controller or MVC type pattern so that the model (the underlying program logic and data) is extracted out of the view (the GUI), you can do a quick and dirty solution just by giving your variables private class scope.
For instance, if the JTextField was called textField and was held in a JPanel that acts as a "card", say called cardPanel, you could create a class that looked something like so:
public class CardPanel extends JPanel {
// constants to give the GUI a bigger size
private static final int PREF_W = 300;
private static final int PREF_H = 100;
// our key JTextField declared at class level
private JTextField textField = new JTextField(20);
// a JLabel to display the previous cardpanel's text
private JLabel label = new JLabel(" ");
// create the JPanel
public CardPanel(String name) {
setName(name);
setBorder(BorderFactory.createTitledBorder("Panel " + name));
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
labelPanel.add(new JLabel("Prior Card's Word: "));
labelPanel.add(label);
setLayout(new BorderLayout());
add(textField, BorderLayout.PAGE_START);
add(labelPanel, BorderLayout.CENTER);
}
// have to jump through this hoop if we want to JTextField to
// have focus when a card is swapped
public void setFocusOnTextField() {
textField.requestFocusInWindow();
textField.selectAll();
}
// to make our GUI larger
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
// allow outside classes to add a listener to the JTextField
public void addActionListener(ActionListener listener) {
textField.addActionListener(listener);
}
// allow outside classes to get text from the text field
public String getTextFieldText() {
return textField.getText();
}
// allow outside classes to put text into the JLabel
public void setLabelText(String text) {
label.setText(text);
}
}
And then we could use it like so:
public class MyCardLayoutDemo extends JPanel {
private static final String[] NAMES = {"One", "Two", "Three", "Four"};
private Map<String, CardPanel> namePanelMap = new HashMap<>();
private CardLayout cardLayout = new CardLayout();
private int nameIndex = 0;
public MyCardLayoutDemo() {
setLayout(cardLayout);
MyListener listener = new MyListener();
for (String name : NAMES) {
CardPanel cardPanel = new CardPanel(name);
cardPanel.addActionListener(listener);
add(cardPanel, name);
namePanelMap.put(name, cardPanel);
}
}
private class MyListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get the current CardPanel
String name = NAMES[nameIndex];
CardPanel currentCard = namePanelMap.get(name);
// advance the name index to get the next CardPanel
nameIndex++;
nameIndex %= NAMES.length;
name = NAMES[nameIndex];
CardPanel nextCard = namePanelMap.get(name);
// get text from current CardPanel
String text = currentCard.getTextFieldText();
nextCard.setLabelText(text); // and put it into next one
// swap cards
cardLayout.show(MyCardLayoutDemo.this, name);
nextCard.setFocusOnTextField();
}
}
private static void createAndShowGui() {
MyCardLayoutDemo mainPanel = new MyCardLayoutDemo();
JFrame frame = new JFrame("My CardLayout Demo");
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());
}
}
I want to create a window(JFrame) and draw a string on it.However, when i run my code the window appears but without the string i want to draw on it. I have made two classes LabelFrame and WebStalker.
Here is my code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.net.*;
public class LabelFrame extends JFrame {
private final JTextField urlString;
private final JButton backButton;
private final JButton loadButton;
private Stack urlStack = new Stack();
String content;
class GraphicPane extends JComponent {
public GraphicPane() {
super();
}
#Override
public void paint(Graphics g) {
g.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 14));
g.drawString("Hello, World!", 30, 20);
}
}
public LabelFrame() {
setTitle("WebStalker");
setSize(600, 600);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setLayout(new FlowLayout());
urlString = new JTextField(30);
backButton = new JButton("Load");
loadButton = new JButton("Back");
GraphicPane gp = new GraphicPane();
this.add(new JLabel("URL"));
this.add(urlString);
this.add(loadButton);
this.add(backButton);
this.add(gp);
TextFieldHandler tHandler = new TextFieldHandler();
ButtonHandler bHandler = new ButtonHandler();
urlString.addActionListener(tHandler);
backButton.addActionListener(bHandler);
loadButton.addActionListener(bHandler);
}
private class TextFieldHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
content = URLReaderFinal.Reading(event.getActionCommand());
}
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == loadButton) {
try {
//remember url for back button
urlStack.push(urlString.getText());
content = URLReaderFinal.Reading(urlString.getText());
} catch (Exception e) {
System.out.println("Unable to load page");
}
} else if (event.getSource() == backButton) {
if (urlStack.size() <= 1) {
return;
}
try {
urlStack.pop();
String urlString = (String)urlStack.peek();
} catch (Exception e) {
System.out.println("Unable to load page");
}
}
}
}
}
And the other class :
import java.awt.*;
import javax.swing.*;
public class WebStalker extends JFrame {
public static void main(String[] args) {
LabelFrame frame = new LabelFrame();
frame.setVisible(true);
}
}
You panel is using a FlowLayout. A FlowLayout respects the preferred size of a component. The preferred size of your custom component is (0, 0) so there is nothing to paint.
Override the getPreferredSize() method to return a proper size for your component.
Also, custom painting is done by overriding the paintComponent() method.
Since you are extending JComponent you should also do a fillRect(...) on the entire size of the component to make sure the background is cleared. It would be easier to extend JPanel, then you can just invoke super.paintComponent() at the start to clear the background.
Read the section from the Swing tutorial on Custom Painting for working example and more information on both of these suggestions.
I'm new so this question may seem incredibly obvious...
I'm am trying to change a border layout in Java so that the center button is a panel/Jtextarea. A panel that reacts when the other panels are pressed by saying "Going *" *being the direction. Then when I press a new button it erases the old and changes to "Going **" ** being the new direction. I have included the current code and a picture of what I'm looking for :)
/*
* BorderLayoutDemo.java
*
*/
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
public class BorderLayoutDemo {
public static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (!(pane.getLayout() instanceof BorderLayout)) {
pane.add(new JLabel("Container doesn't use BorderLayout!"));
return;
}
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(
java.awt.ComponentOrientation.RIGHT_TO_LEFT);
}
JButton button = new JButton("Up");
pane.add(button, BorderLayout.PAGE_START);
//Make the center component 400x400
//typical usage of BorderLayout.
button = new JButton("Going...");
pane.setPreferredSize(new Dimension(400, 400));
pane.add(button, BorderLayout.CENTER);
button = new JButton("Left");
pane.add(button, BorderLayout.LINE_START);
button = new JButton("Down");
pane.add(button, BorderLayout.PAGE_END);
button = new JButton("Right");
pane.add(button, BorderLayout.LINE_END);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("BorderLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Use the content pane's default BorderLayout. No need for
//setLayout(new BorderLayout());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You need to give a unique field name to the JButton in the center.
goingButton = new JButton("Going...");
pane.add(goingButton, BorderLayout.CENTER);
Then you need to write an action listener for the other buttons that change the text of the goingButton. Here's how you set the text of a JButton.
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
goingButton.setText("Going up");
}
});
Edited to just give you the modified code. You're not going to learn anything if others do your work for you.
Here's a screen shot of the BorderLayoutDemo.
And here's the code, formatted and modified for you:
package com.ggl.testing;
/*
* BorderLayoutDemo.java
*
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BorderLayoutDemo {
private static final boolean RIGHT_TO_LEFT = false;
private JButton goingButton;
public void addComponentsToPane(Container pane) {
if (!(pane.getLayout() instanceof BorderLayout)) {
pane.add(new JLabel("Container doesn't use BorderLayout!"));
return;
}
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Up");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
goingButton.setText("Going up");
}
});
pane.add(button, BorderLayout.PAGE_START);
// Make the center component 400x400
// typical usage of BorderLayout.
goingButton = new JButton("Going...");
goingButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
goingButton.setText("Going crazy");
}
});
pane.add(goingButton, BorderLayout.CENTER);
button = new JButton("Left");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
goingButton.setText("Going left");
}
});
pane.add(button, BorderLayout.LINE_START);
button = new JButton("Down");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
goingButton.setText("Going down");
}
});
pane.add(button, BorderLayout.PAGE_END);
button = new JButton("Right");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
goingButton.setText("Going right");
}
});
pane.add(button, BorderLayout.LINE_END);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
*/
private void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("BorderLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
// Use the content pane's default BorderLayout. No need for
// setLayout(new BorderLayout());
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
// Schedule a job for the event dispatch thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BorderLayoutDemo().createAndShowGUI();
}
});
}
}
I'm a java beginner and I tried making a basic program that will delete a certain file in the temp files in Windows. It did delete the file without a problem when I hadn't implemented the JPanel & JFrame but I haven't had any luck since. It is supposed to delete the file when the "Delete for sure" jbutton is pressed and exit the program when the "exit" jbutton is pressed. All it does right now is bring up the GUI and nothing else. Not even system out prints. Here is the code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Andrew
* Date: 12/4/12
* Time: 7:09 PM
* To change this template use File | Settings | File Templates.
*/
public class DeleteFile {
public static void main (String args[]) throws IOException {
frame.setVisible(true);
frame.setName(boxname);
frame.setSize(100, 150);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
button1.setText(buttontext);
button1.setVisible(true);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
deleteFile();
JLabel label = new JLabel("Deletion was successful");
JPanel panel = new JPanel();
panel.add(label);
}
}
class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
public void windowEvent (WindowEvent e) {
System.exit(0);
}
}
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Delete for sure?");
panel.add(button);
button.addActionListener (new Action1());
panel.setName(boxname);
JButton button2 = new JButton("Exit");
panel.add(button2);
button2.addActionListener (new Action2());
// JLabel label = new JLabel(filePath);
// panel.add(label);
}
static String buttontext = "Delete file for sure?";
static String boxname = "Trepix Temp File Deleter";
static String filePath = "C:\\Users\\Andrew\\AppData\\Local\\Temp\\CamRec0\\cursor-1.ico";
static JFrame frame = new JFrame();
static JButton button1 = new JButton();
static JPanel panel = new JPanel();
public static boolean fileIsValid() {
File file = new File(filePath);
if (file.exists()) {
return true;
} else {
return false;
}
}
public static void deleteFile() {
if (fileIsValid() == true) {
File file = new File(filePath);
file.delete();
}
}
}
class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
deleteFile();
JLabel label = new JLabel("Deletion was successful");
JPanel panel = new JPanel();
panel.add(label);
}
}
The panel object is never placed in any container that is part of a hierarchy leading to a top-level window. In other words, it's not placed in anything that is sitting in either a JFrame or JDialog, and so it will never be displayed.
class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
}
public void windowEvent (WindowEvent e) {
System.exit(0);
}
}
It makes no sense to place this windowEvent method in an ActionListener, since that is part of a WindowListener, something completely different. Why not simply call System.exit(0); in the actionPerformed(...) method?
Also your code shouldn't have any static fields or methods as that is antithetical to object-oriented programming.
I'm trying to create a java GUI that outputs a value once the value is selected from a drop down and the apply button is pressed. The problem is this is my first time creating a GUI in java, I just used some sample code I found and reworked it, but I'm unsure how to output the value I want. The code is below and the value I want to output is "colour".
package state;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
Font font = new Font("Cambria", Font.PLAIN, 20);
static final String Colour[] = {"Blue", "Yellow"};
static final String Pitch[] = {"Main Pitch", "Side Pitch"};
final static int maxGap = 20;
JComboBox colourComboBox;
JComboBox pitchComboBox;
Label colourLabel;
Label pitchLabel;
JButton applyButton = new JButton("Apply settings");
GridLayout experimentLayout = new GridLayout(0,2);
public GUI(String name) {
super(name);
setResizable(false);
}
public void initGaps() {
colourComboBox = new JComboBox(Colour);
colourComboBox.setFont(font);
pitchComboBox = new JComboBox(Pitch);
pitchComboBox.setFont(font);
}
public void addComponentsToPane(final Container pane) {
initGaps();
final JPanel compsToExperiment = new JPanel();
compsToExperiment.setLayout(experimentLayout);
JPanel controls = new JPanel();
controls.setLayout(new GridLayout(0,2));
//Set up components preferred size
JButton b = new JButton("Just fake button");
Dimension buttonSize = b.getPreferredSize();
compsToExperiment.setPreferredSize(new Dimension((int)(buttonSize.getWidth() * 3.3)+maxGap,
(int)(buttonSize.getHeight() * 1.5)+maxGap * 5));
//Add buttons to experiment with Grid Layout
colourLabel = new Label("Select Robot Colour:");
colourLabel.setFont(font);
pitchLabel = new Label("Select Pitch:");
pitchLabel.setFont(font);
compsToExperiment.add(colourLabel);
compsToExperiment.add(colourComboBox);
compsToExperiment.add(pitchLabel);
compsToExperiment.add(pitchComboBox);
controls.add(applyButton);
//Process the Apply gaps button press
applyButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String colour = (String)colourComboBox.getSelectedItem();
String pitch = (String)pitchComboBox.getSelectedItem();
}
});
pane.add(compsToExperiment, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(controls, BorderLayout.SOUTH);
}
/**
* Create the GUI and show it. For thread safety,
* this method is invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
GUI frame = new GUI("Match Conditions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You can get the text using the getSelectedItem() function in JComboBox.
ex.
pitchComboBox.getSelectedItem().toString()
colourComboBox.getSelectedItem().toString()
Show Output as in ??
You can use this...
JOptionPane.showMessageDialog(null, "Colour"+colour); to show it in a dialog.