I'm making a simple text editor in Java and for some reason my find and replace actions won't work, i made two separate frames, one for the find action, and the other to open up another frame with 2 jtextfields for find and replace. i have in my actionperformed
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
and in my findFrame i have the action that should be carried out when the user clicks on the JMenuItem called "Find".
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
In my Replace frame where i want the user to find a word and replace it, anything you type into the find textfield and click the find button, it finds the first 3 characters on the text field, and the replace action just doesn't work at all,
here is my replace frame
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
the find and replace are two separate JMenuItems, when the user clicks on Find it opens up findframe and when they click on "replace" it opens up the replace frame which has a find textfield and a replace textfield.
here is the whole runnable code :
//Programmer Aly Badran – Project 10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultEditorKit.CutAction;
class saveFrame extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel labelpanel = new JPanel();
JButton savebutton = new JButton("Save");
JButton dontsave = new JButton("Dont Save");
JLabel savelabel = new JLabel("Are you sure you want to close"?);
public saveFrame(){
setSize(400,100);
setLocation(500, 300);
setTitle("Saving...");
labelpanel.add(savelabel);
panel.add(savebutton);
panel.add(dontsave);
Container cpane = getContentPane();
cpane.add(panel, "South");
cpane.add(labelpanel, "Center");
setVisible(true);
savebutton.addActionListener(this);
dontsave.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == savebutton){
System.exit(0);
}
else if(source == dontsave){
System.exit(0);
}
}
}
class replaceFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JButton replace = new JButton("Replace");
JTextField replacetext = new JTextField("Enter text to replace", 20);
JTextField findtext = new JTextField("Enter text to find", 20);
replaceFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Replace");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
panel.add(replace);
panel.add(replacetext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
replace.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = find.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
if(command.equals("Find")){
MenuFrame.textarea.select(n,n+search.length());
}
if(command.equals("Replace")){
MenuFrame.textarea.replaceRange(replacing, n, n+search.length());
}
}
}
class MenuFrame extends JFrame implements ActionListener, MouseListener{
static JTextArea textarea = new JTextArea();
static JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenuItem copy = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cut = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem Paste = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenuItem copyAction = new JMenuItem(new DefaultEditorKit.CopyAction());
JMenuItem cutAction = new JMenuItem(new DefaultEditorKit.CutAction());
JMenuItem pasteAction = new JMenuItem(new DefaultEditorKit.PasteAction());
JMenu search = new JMenu("Search");
JMenuItem open = new JMenuItem("Open");
JMenuItem close = new JMenuItem("Close");
JMenuItem quit = new JMenuItem("Quit");
JMenuItem find = new JMenuItem("Find");
JMenuItem replace = new JMenuItem("Replace");
JMenu font = new JMenu("Font");
JCheckBoxMenuItem bold = new JCheckBoxMenuItem("Bold");
JCheckBoxMenuItem italic = new JCheckBoxMenuItem("Italic");
JPopupMenu popup;
public MenuFrame(){
Container cpane = getContentPane();
cpane.add(textarea);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenheight = d.height;
int screenwidth = d.width;
setSize(screenwidth, screenheight);
JPanel panel = new JPanel();
ImageIcon closeicon = new ImageIcon("bin/close.png");
ImageIcon openicon = new ImageIcon("bin/open.png");
ImageIcon quiticon = new ImageIcon("bin/quit.jpeg");
ImageIcon findicon = new ImageIcon("bin/find.png");
ImageIcon replaceicon = new ImageIcon("bin/replace.png");
ImageIcon boldicon = new ImageIcon("bin/bold.png");
ImageIcon italicicon = new ImageIcon("bin/italic.png");
ImageIcon copyicon = new ImageIcon("bin/copy.png");
ImageIcon cuticon = new ImageIcon("bin/cut.png");
ImageIcon pasteicon = new ImageIcon("bin/paste.png");
Border matte = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK);
Border etched = BorderFactory.createEtchedBorder();
popup = new JPopupMenu();
copy.setText("Copy");
cut.setText("Cut");
Paste.setText("Paste");
copy.setIcon(copyicon);
cut.setIcon(cuticon);
Paste.setIcon(pasteicon);
copyAction.setText("Copy");
cutAction.setText("Cut");
pasteAction.setText("Paste");
copyAction.setIcon(copyicon);
cutAction.setIcon(cuticon);
pasteAction.setIcon(pasteicon);
popup.add(cut);
popup.addSeparator();
popup.add(copy);
popup.addSeparator();
popup.add(Paste);
popup.addSeparator();
popup.add(find);
popup.addSeparator();
popup.add(replace);
edit.add(cutAction);
edit.addSeparator();
edit.add(copyAction);
edit.addSeparator();
edit.add(pasteAction);
find.setIcon(findicon);
replace.setIcon(replaceicon);
close.setIcon(closeicon);
menubar = new JMenuBar();
textarea = new JTextArea("He has achieved success.", d.width, d.height);
JScrollPane scroll = new JScrollPane(textarea);
cpane.add(scroll);
open = new JMenuItem("Open", openicon);
close = new JMenuItem("Close", closeicon);
quit = new JMenuItem("Quit", quiticon);
find = new JMenuItem("Find", findicon);
replace = new JMenuItem("Replace", replaceicon);
bold = new JCheckBoxMenuItem("Bold", boldicon);
italic = new JCheckBoxMenuItem("Italic", italicicon);
textarea.setLineWrap(true);
file.add(open);
file.addSeparator();
file.add(close);
file.addSeparator();
file.add(quit);
menubar.add(file);
menubar.add(edit);
menubar.add(search);
menubar.add(font);
search.add(find);
search.addSeparator();
search.add(replace);
font.add(bold);
font.addSeparator();
font.add(italic);
copy.setEnabled(false);
cut.setEnabled(false);
Paste.setEnabled(false);
find.addActionListener(this);
italic.addActionListener(this);
bold.addActionListener(this);
quit.addActionListener(this);
close.addActionListener(this);
find.addActionListener(this);
replace.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
Paste.addActionListener(this);
cut.addMouseListener(this);
textarea.addMouseListener(this);
copy.addMouseListener(this);
Paste.addMouseListener(this);
textarea.setComponentPopupMenu(popup);
file.setBackground(Color.BLACK);
edit.setBackground(Color.BLACK);
search.setBackground(Color.BLACK);
font.setBackground(Color.BLACK);
panel.add(menubar);
menubar.setBorder(matte);
menubar.setBackground(Color.BLACK);
textarea.setBorder(etched);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
String command = evt.getActionCommand();
String s = textarea.getSelectedText();
Font f = new Font("Italic", Font.ITALIC, 13);
Font f2 = new Font("Bold", Font.BOLD, 13);
if(italic.isSelected()){
textarea.setFont(f);
}
if(bold.isSelected()){
textarea.setFont(f2);
}
if(bold.isSelected() && italic.isSelected()){
textarea.setFont(f);
textarea.setFont(f2);
}
if(command.equals("Quit"))
System.exit(0);
if(command.equals("Close")){
JFrame frame = new saveFrame();
frame.setVisible(true);
}
if(source == find){
JFrame frame = new FindFrame();
frame.setVisible(true);
}
if(command.equals("Replace")){
JFrame frame2 = new replaceFrame();
frame2.setVisible(true);
}
}
public void mouseClicked(MouseEvent e) {
boolean s = textarea.getSelectedText() != null;
if(s){
copy.setEnabled(true);
cut.setEnabled(true);
Paste.setEnabled(true);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
class FindFrame extends JFrame implements ActionListener{
JButton find = new JButton("Find");
JTextField findtext = new JTextField("Find What", 20);
FindFrame(){
setSize(400, 100);
setLocation(500, 300);
setTitle("Find...");
JPanel panel = new JPanel();
panel.add(find);
panel.add(findtext);
Container cpane = getContentPane();
cpane.add(panel, "Center");
setVisible(true);
find.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
String command = evt.getActionCommand();
String search = findtext.getText();
int n = textarea.getText().indexOf(search);
if(source == find){
MenuFrame.textarea.select(n,n+search.length());
}
}
}
}
public class Menus {
public static void main(String [] args){
JFrame frame = new MenuFrame();
frame.setJMenuBar(MenuFrame.menubar);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Your basic problem comes down to the fact that the "selection" highlight won't be painted while the JTextArea doesn't have focus, I know, awesome.
However, you could use a Highlighter instead, for example...
if (source == find) {
try {
DefaultHighlighter.DefaultHighlightPainter highlighter = new DefaultHighlighter.DefaultHighlightPainter(UIManager.getColor("TextArea.selectionBackground"));
MenuFrame.textarea.getHighlighter().addHighlight(n, n + search.length(), highlighter);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
Which will paint a "highlight" over the specified area.
You may want to have a look at this for away to remove it
This and this may also be of interest
In your replace method, you are using the text of the find JButton instead of the findtext JTextField
//String search = find.getText();
String search = findtext.getText();
String replacing = replacetext.getText();
int n = MenuFrame.textarea.getText().indexOf(search);
Your codes also a mess (sorry, took me a while to navigate it).
For example, you're adding a ActionListener twice to the find menu item and probably some others, which caused to find windows to appear.
I'd avoid using Toolkit#getScreenSize(); in connection with JFrame#setSize, a better solution would be to use JFrame#setExtendedState and pass it JFrame#MAXIMIZED_BOTH, as this will also take into consideration the other UI assets that the OS may have fixed on the screen (like docks and task bars).
You really should be using dialogs instead of JFrames for your "short term input" mechanisms
Your also recreating a bunch of stuff you've already created, for example...
static JTextArea textarea = new JTextArea();
//...
textarea = new JTextArea("He has achieved success.", d.width, d.height);
What's worse, is you add the original instance of the textarea to the frame BEFORE you create the new one, which runs the risk of not knowing which component you are actually dealing with...which is just compounded by the fact that you're using a static reference to it so other classes can access it, which they shouldn't be allowed to do...
In replaceFrame, you are taking text to search from the find field (button), but you should take it from findtext (you are always searching for text "Find").
This is one of the reasons why code duplication is bad - you should extract the finding logic to one place and reuse it in both classes.
Related
3 Classes - GUI, ImageLoader and Wizard
GUI is the main frame whereas Wizard is just a popup that changes settings and imageloader is image handler
What I want is to load image from wizard to Jlabel on my main GUI but I have no idea where to start and never had experience with loading images onto GUI. Searching for answer on here didn't really help, it just create more confusion for me. I would appreciate if you also can add explanations as well.
GUI -
public class GUI extends JPanel{
//variables
JFrame frame = new JFrame("All-in-one Application");
JMenuBar menuBar;
JMenu file, edit, help, about;
JMenuItem settings, startWizard, exit, save, load, readme;
JLabel imgLabel;
private Wizard wiz;
public void topMenuBar(){
//creating the menubar
menuBar = new JMenuBar();
//Menu
file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");
about = new JMenu("About");
//MenuItems
startWizard = new JMenuItem("Start Wizard");
//listener for wizard
Wizard wiz = new Wizard();
// GUIListener gListener = new GUIListener();
startWizard.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
wiz.startWizardd();
}
});
settings = new JMenuItem("Settings");
readme = new JMenuItem("Read Me");
exit = new JMenuItem("Exit");
save = new JMenuItem("Save");
load = new JMenuItem("Load");
//jbutton
// test = new JButton("Test");
//adding MenuItems to the Menu
/**file**/
file.add(startWizard);
file.add(new JSeparator());
file.add(save);
file.add(load);
file.add(new JSeparator());
file.add(exit);
//end file
//edit
edit.add(settings);
//help
help.add(readme);
//about
//Adding Menu to the menu bar
menuBar.add(file);
menuBar.add(edit);
menuBar.add(help);
menuBar.add(about);
//exit action listener
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public void mainPanel(){
FlowLayout main = new FlowLayout();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(main);
//jlabel
imgLabel = new JLabel("img");
mainPanel.add(imgLabel);
frame.add(mainPanel, BorderLayout.CENTER);
}
//intiate GUI
public void intGUI(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300,0);
frame.setSize(1400,1000);
topMenuBar();
mainPanel();
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
}
Wizard:
public class Wizard extends JPanel{
//variables
private ImageLoader imgload = new ImageLoader(this);
private JButton applyButton, nextButton, backButton, cancelButton, openMapButton;
JDialog wizDialog;
JFrame wizFrame;
JLabel siteNameLabel, siteMapLabel, AisleNumLabel, laneNumLabel, label;
JTextField siteNameField, aisleNumField, laneNumField;
private JTextField mapURLField = new JTextField(20);
JFileChooser chooser;
private File file;
String fileName;
BufferedImage img; // private JPanel addInfoPanel, controlPanel;
public void startWizardd(){
System.out.println("Starting Wizard....");
wizardGUI();
}
public void wizardCmpt()
{
//setting the panel up with gridlayout settings
FlowLayout map = new FlowLayout();
JPanel mapPanel = new JPanel();
mapPanel.setLayout(map);
FlowLayout grid = new FlowLayout();
JPanel addInfoPanel = new JPanel();
addInfoPanel.setLayout(grid);
FlowLayout controls = new FlowLayout();
JPanel controlPanel = new JPanel();
controlPanel.setLayout(controls);
//buttons
JButton openMapButton = new JButton("Load Map");
openMapButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
imgload.fileChooser();
}
});
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton nextButton = new JButton("Next");
JButton backButton = new JButton("Back");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
wizFrame.setVisible(false);
wizFrame.dispose();
}
});
//jlabels
JLabel siteNameLabel = new JLabel("Site Name :");
JLabel siteMapLabel = new JLabel("Site Map :");
JLabel AisleNumLabel = new JLabel("Number of Aisles :");
JLabel laneNumLabel = new JLabel("Number of Lanes :");
//jtextfield
JTextField siteNameField = new JTextField(5);
JTextField aisleNumField = new JTextField(5);
JTextField laneNumField = new JTextField(5);
//adding to GUI
addInfoPanel.add(siteNameLabel);
addInfoPanel.add(siteNameField);
addInfoPanel.add(AisleNumLabel);
addInfoPanel.add(aisleNumField);
addInfoPanel.add(laneNumLabel);
addInfoPanel.add(laneNumField);
mapPanel.add(siteMapLabel);
mapPanel.add(mapURLField);
mapPanel.add(openMapButton);
controlPanel.add(applyButton);
// controlPanel.add(nextButton);
// controlPanel.add(backButton);
controlPanel.add(cancelButton);
wizFrame.add(addInfoPanel, BorderLayout.NORTH);
wizFrame.add(mapPanel, BorderLayout.CENTER);
wizFrame.add(controlPanel, BorderLayout.SOUTH);
}
public void setMapUrlField(String text){
mapURLField.setText(text);
}
public File getFile(){
return file;
}
private void wizardGUI(){
System.out.println("it's loading");
wizFrame = new JFrame("Wizard Operation");
wizFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
wizFrame.setSize(600,600);
wizardCmpt();
wizFrame.pack();
wizFrame.setVisible(true); } }
Image Loader:
public class ImageLoader{
private JLabel label;
JFileChooser chooser;
File file;
private BufferedImage img;
private Wizard wiz;
public ImageLoader(Wizard wiz){
this.wiz = wiz;
}
public File fileChooser(){
File file = null;
JFileChooser fileChooser = new JFileChooser();
FileFilter imageFilter = new FileNameExtensionFilter("Image files ", ImageIO.getReaderFileSuffixes());
fileChooser.setFileFilter(imageFilter);
int retValue = fileChooser.showOpenDialog(wiz);
if(retValue == JFileChooser.APPROVE_OPTION){
file = fileChooser.getSelectedFile();
wiz.setMapUrlField(file.getAbsolutePath());
}else{
wiz.setMapUrlField("");
}
return file;
}
}
I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Firstly capitalize the name of your class always in Java, then check this code :
public class Sim extends JPanel {
public Sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/1.png");
Icon c = new ImageIcon("/home/mehdi/Pictures/ICONS/Test/2.png");
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
final JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
button.addActionListener(new HandlerClass(label));
}
private class HandlerClass implements ActionListener{
final JLabel label;
public HandlerClass(JLabel label){
this.label = label;
}
public void actionPerformed(ActionEvent e)
{
label.setText("SSSSSSSSSSSSSsssss");
JOptionPane.showMessageDialog(null, "Something");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new Sim());
frame.setVisible(true);
}
}
the mission here is to create JButtons from a String in ActionListener, but we need a way to refresh the GUI panel so it know that there is now variable for the button creater in the GUI. i have a feeling that the button creater must be in ActionListener and there is a command like repaint() or removeAll that is missing inside the ActionListener.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("number of buttons");
JMenuBar meny = new JMenuBar();
JMenu fil = new JMenu("somthing");
JMenuItem angre = new JMenuItem("deleate on button");
JMenuItem angre2 = new JMenuItem("deleate all buttons");
int d;
int i;
public GUI(){
this.setTitle("somthing");
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setJMenuBar(meny);
meny.add(fil);
fil.add(angre2);
fil.add(angre);
angre2.addActionListener(this);
angre.addActionListener(this);
AntallTurneringer.addActionListener(this);
this.add(AntallTurneringer);
AntallTurneringer.setVisible(true);
if(d > 0){
turneringer = new JButton[d];
for(i = 0; i < d; i++){
turneringer[d] = new JButton();
turneringer[d].addActionListener(this);
turneringer[d].setText("Turnering "+(i+1));
turneringer[d].setVisible(true);
this.add(turneringer[d]);
}}
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons");
d = Integer.parseInt(tu);
}
}
You could use a separate panel for the buttons. would simplify the whole thing.
private JPanel buttonPnl;
public void actionPerformed(ActionEvent e){
buttonPnl.invalidate();
buttonPnl.clear();
//create the new buttons
buttonPnl.validate();
buttonPnl.repaint();
}
I have solved it, it were no need for repainting or clearing anything. the first problem in the code were that i had used [d] inside the array, and not[i]. the second problem were the placement of the for loop. this is the working code under.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("Velg antall turneringer");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
int d;
public GUI(){
this.setTitle("Squash Turnering");
this.setLayout(new GridLayout());
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.RED);
AntallTurneringer.addActionListener(this);
AntallTurneringer.setVisible(true);
panel1.add(AntallTurneringer);
add(panel1);
add(panel2);
panel2.setVisible(false);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons you want to add");
d = Integer.parseInt(tu);
turneringer = new JButton[d];
for(int i = 0; i < d; i++){
turneringer[i] = new JButton();
turneringer[i].addActionListener(this);
turneringer[i].setText("Turnering "+(i+1));
turneringer[i].setVisible(true);
turneringer[i].setSize(100, 100);
panel2.add(turneringer[i]);
}
panel1.setVisible(false);
panel2.setVisible(true);
}
}}
I am trying to make a program that reads a file chosen by the user, and after reading the file - the suffix "txt" is changed to "gif" and the file is saved as a picture (which is in the same catalogue as the file). The thing is, this picture variable gets its value in the "actionPerformed-method" and after that I want to add it to a frame in another class- but it doesn't show. Here's the code in my OptionsPane-class:
public class OptionsPane extends JComponent implements ActionListener{
private JButton buttonOne = new JButton("Alt.1");
private JButton buttonTwo = new JButton("Alt.2");
private JButton buttonThree = new JButton("Alt.3");
private int option;
private JButton buttonChoose = new JButton("Choose file");
private FileHandler filehandler;
private String picture;
private JLabel picLabel;
public OptionsPane(){
JLabel label = new JLabel("Choose optimization method", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
label.setForeground(Color.CYAN);
label.setFont(new Font("Tahoma", Font.BOLD, 15));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(label);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonChoose.addActionListener(this);
subPanel.setBackground(Color.DARK_GRAY);
subPanel.add(buttonOne);
subPanel.add(buttonTwo);
subPanel.add(buttonThree);
subPanel.add(buttonChoose);
this.add(subPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOne){
option = 1;
System.out.println("You clicked button 1!");
}else if(e.getSource() == buttonTwo){
option = 2;
System.out.println("You clicked button 2!");
}else if(e.getSource() == buttonThree){
option = 3;
System.out.println("You clicked button 3!");
}else if(e.getSource() == buttonChoose){
System.out.println("hello");
option = 4;
filehandler = new FileHandler();
filehandler.read();
picture = filehandler.getFilePath().replaceFirst("txt", "gif");
picLabel = new JLabel(new ImageIcon(picture));
this.add(picLabel);
}
}
}
The frame is in the "MainFrame"-class, which looks like this at the moment:
public class MainFrame extends JFrame{
private JFrame frame = new JFrame();
private String picture;
private JLabel picLabel;
public MainFrame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1300, 800));
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
OptionsPane optionspane = new OptionsPane();
frame.add(optionspane);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
}
Why isn't the picture visible in the mainframe?
EDIT
It works now!
https://stackoverflow.com/a/22380387/3271504
Thank you for your help #arooaroo . I tried to write down some of what you wrote, but it still didn't work when I wanted to add an image based on what file the user had chosen (for example if the user chose file text1.txt i wanted the corresponding picture "text1.gif" to show up). With your help, the picture showed up when I typed a specific pathway with "/"-slashes, but when I chose a file and tried to load the picture from the file pathway, it didn't show and that is because it had backslashes in the pathways. This is how it should be (such an irritating problem):
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonOne){
option = 1;
System.out.println("You clicked button 1!");
}else if(e.getSource() == buttonTwo){
option = 2;
System.out.println("You clicked button 2!");
}else if(e.getSource() == buttonThree){
option = 3;
System.out.println("You clicked button 3!");
}else if(e.getSource() == buttonChoose){
filehandler = new FileHandler();
filehandler.read();
filepath = filehandler.getFilePath();
picture = filepath.replaceFirst("txt", "gif");
picture = picture.replaceAll("\\\\", "/");
ImageIcon icon = new ImageIcon(picture);
mainFrame.setPicture(icon);
}
Thank you for your help!
Once you separate your GUI code in to separate classes - which is a Good Thing - you will find the eternal challenge for GUI programming is allowing for clean communication between them where there are inter-dependencies.
In this instance perhaps the simplest approach is to pass in a reference of MainFrame into OptionsPane.
Let's assume you create an additional method in MainFrame for setting the picture:
public class MainFrame extends JFrame{
// all instance vars as before
public MainFrame() {
// same as before except for this line...
OptionsPane optionspane = new OptionsPane(this);
}
public void setPicture(JLabel pictureLabel) {
// add code here for adding the picture...
// That's an exercise for yourself, or another question ;)
}
}
Then in your OptionsPane class:
....
private MainFrame mainFrame; // add a new instance var
public OptionsPane(MainFrame mainFrame) {
this.mainFrame = mainFrame;
// ... rest of the code same as before
}
#Override
public void actionPerformed(ActionEvent e) {
//...
picture = filehandler.getFilePath().replaceFirst("txt", "gif");
picLabel = new JLabel(new ImageIcon(picture));
mainFrame.setPicture(picLabel); // <-- This is where you communicate with the mainFrame instance
//...
}
EDIT
Although my original answer provided a valid and correct solution, it's clear that the OP requires a fully working example, including the code to load display the resulting image. Here's a sample program.
public class OptionsPane extends JComponent implements ActionListener {
private JButton buttonOne = new JButton("Alt.1");
private JButton buttonTwo = new JButton("Alt.2");
private JButton buttonThree = new JButton("Alt.3");
private int option;
private JButton buttonChoose = new JButton("Choose file");
private String picture;
private JLabel picLabel;
private MainFrame mainFrame;
public OptionsPane(MainFrame mainFrame) {
this.mainFrame = mainFrame;
JLabel label = new JLabel("Choose optimization method", SwingConstants.CENTER);
JPanel subPanel = new JPanel();
label.setForeground(Color.CYAN);
label.setFont(new Font("Tahoma", Font.BOLD, 15));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(label);
buttonOne.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonChoose.addActionListener(this);
subPanel.setBackground(Color.DARK_GRAY);
subPanel.add(buttonOne);
subPanel.add(buttonTwo);
subPanel.add(buttonThree);
subPanel.add(buttonChoose);
this.add(subPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
// For sake of simplicity I'm ignoring the original button logic here
// and focussing on just getting an icon loaded in the parent frame...
ImageIcon icon = new ImageIcon("/path/to/test/image.png");
// Just pass the icon itself rather than a new label.
mainFrame.setPicture(icon);
}
}
public class MainFrame {
// No need to extend JFrame if you're using a JFrame instance variable
private JFrame frame = new JFrame();
private JLabel picLabel;
private JPanel mainPanel;
public MainFrame() {
mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(Color.DARK_GRAY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1300, 800));
OptionsPane optionspane = new OptionsPane(this);
mainPanel.add(optionspane, BorderLayout.NORTH);
picLabel = new JLabel();
picLabel.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(picLabel, BorderLayout.CENTER);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
public void setPicture(ImageIcon icon) {
picLabel.setIcon(icon);
}
public static void main(String[] args) {
new MainFrame();
}
}
Note I've done a couple of things differently. Personally I always create a JPanel and set that up as the primary layer rather and add that directly to the frame rather than messing with the rootPane. And I used the BorderLayout in this example as it's much simpler.
The other thing is to add the JLabel which is to hold the picture to the GUI in the initial set up. Then you'll see I'm only changing its icon in the setPicture() method rather than adding a new JLabel on each instance.
I tried using:
frame1.getContentPane().setBackground(Color.yellow);
But it is not working. Can anyone help me?
import java.awt.*;
import java.awt.Color;
public class PlayGame {
public static void main(String[] args) {
GameFrame frame1 = new GameFrame();
frame1.getContentPane().setBackground(Color.yellow);
// Set Icon
Image icon = Toolkit.getDefaultToolkit().getImage("image/poker_icon.gif");
frame1.setIconImage(icon);
frame1.setVisible(true);
frame1.setSize(600, 700);
frame1.setTitle("Card Game");
// Set to exit on close
frame1.setDefaultCloseOperation(GameFrame.EXIT_ON_CLOSE);
}
}
GameFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GameFrame extends JFrame implements ActionListener {
private JPanel topPnl, btmPnl, pcPnl, mainPnl;
private JPanel titlePnl, playerPnl, computerPnl;
private JLabel titleLbl, playerLbl, computerLbl;
private JLabel testTextBox1, testTextBox2;
private ImageIcon playerIcon, computerIcon;
//
private JPanel pickCardPnl, pickCardTitlePnl, cardPnl, resultPnl, optionPnl;
private JLabel pickCardTitleLbl;
private JLabel card1Lbl, card2Lbl, card3Lbl, card4Lbl, card5Lbl;
private JLabel resultLbl;
private JButton restartBtn, showCardBtn, exitBtn;
private JButton card1Btn, card2Btn, card3Btn, card4Btn, card5Btn;
private ImageIcon card1Pic, card2Pic, card3Pic, card4Pic, card5Pic;
private JButton playerBtn, computerBtn;
private ImageIcon playerPic;
private String[] card = new String[53];
private String name;
// ArrayInt al;
public GameFrame() {
// a1 = new Array();
//a1.generateRandom();
setCard();
setName();
// Top Panel /////////////////////////////////////
mainPnl = new JPanel(new BorderLayout());
topPnl = new JPanel(new BorderLayout(50, 0));
titlePnl = new JPanel();
pcPnl = new JPanel(new GridLayout(1, 2, 10, 10));
playerPnl = new JPanel(new BorderLayout(10, 10));
computerPnl = new JPanel(new BorderLayout(10, 10));
// Title Panel
titleLbl = new JLabel("Card Game");
titlePnl.add(titleLbl);
// Player Panel
playerIcon = new ImageIcon("image/player.png");
playerLbl = new JLabel(name, playerIcon, JLabel.CENTER);
playerPnl.add(playerLbl, BorderLayout.NORTH);
playerPic = new ImageIcon("image/unknwon.png");
playerBtn = new JButton(playerPic);
playerPnl.add(playerBtn, BorderLayout.CENTER);
playerBtn.setContentAreaFilled(false);
playerBtn.setBorder(BorderFactory.createEmptyBorder());
// Computer Panel
computerIcon = new ImageIcon("image/computer.png");
computerLbl = new JLabel("Computer:", computerIcon, JLabel.CENTER);
computerPnl.add(computerLbl, BorderLayout.NORTH);
playerPic = new ImageIcon("image/back.png");
computerBtn = new JButton(playerPic);
computerPnl.add(computerBtn, BorderLayout.CENTER);
computerBtn.setContentAreaFilled(false);
computerBtn.setBorder(BorderFactory.createEmptyBorder());
pcPnl.add(playerPnl);
pcPnl.add(computerPnl);
// Add panel into Top Panel
topPnl.add(titlePnl, BorderLayout.NORTH);
topPnl.add(pcPnl, BorderLayout.CENTER);
// Bottom Panel /////////////////////////////////////
btmPnl = new JPanel(new BorderLayout());
pickCardPnl = new JPanel(new BorderLayout());
pickCardTitlePnl = new JPanel();
cardPnl = new JPanel(new GridLayout(1, 5, 5, 5));
resultPnl = new JPanel();
optionPnl = new JPanel(new GridLayout(1, 3, 5, 5));
// Pick Card Panel
pickCardTitleLbl = new JLabel("Pick Your Card:");
pickCardPnl.add(pickCardTitleLbl, BorderLayout.NORTH);
card1Pic = new ImageIcon(card[1]);
card1Btn = new JButton(card1Pic);
cardPnl.add(card1Btn);
card1Btn.addActionListener(this);
card2Pic = new ImageIcon(card[2]);
card2Btn = new JButton(card2Pic);
cardPnl.add(card2Btn);
card2Btn.addActionListener(this);
card3Pic = new ImageIcon(card[3]);
card3Btn = new JButton(card3Pic);
cardPnl.add(card3Btn);
card3Btn.addActionListener(this);
card4Pic = new ImageIcon(card[4]);
card4Btn = new JButton(card4Pic);
cardPnl.add(card4Btn);
card4Btn.addActionListener(this);
card5Pic = new ImageIcon(card[5]);
card5Btn = new JButton(card5Pic);
cardPnl.add(card5Btn);
card5Btn.addActionListener(this);
// new ImageIcon(a1.getRandomNumber);
pickCardPnl.add(cardPnl, BorderLayout.CENTER);
card1Btn.setContentAreaFilled(false);
card1Btn.setBorder(BorderFactory.createEmptyBorder());
card2Btn.setContentAreaFilled(false);
card2Btn.setBorder(BorderFactory.createEmptyBorder());
card3Btn.setContentAreaFilled(false);
card3Btn.setBorder(BorderFactory.createEmptyBorder());
card4Btn.setContentAreaFilled(false);
card4Btn.setBorder(BorderFactory.createEmptyBorder());
card5Btn.setContentAreaFilled(false);
card5Btn.setBorder(BorderFactory.createEmptyBorder());
// Result Panel
setCard();
resultLbl = new JLabel("adasdadadasdasdasdasd");
resultPnl.add(resultLbl);
// Option Panel
restartBtn = new JButton("Restart");
optionPnl.add(restartBtn);
restartBtn.addActionListener(this);
showCardBtn = new JButton("Show Cards");
optionPnl.add(showCardBtn);
showCardBtn.addActionListener(this);
exitBtn = new JButton("Exit");
optionPnl.add(exitBtn);
exitBtn.addActionListener(this);
// Add panel into Bottom Panel
btmPnl.add(pickCardPnl, BorderLayout.NORTH);
btmPnl.add(resultPnl, BorderLayout.CENTER);
btmPnl.add(optionPnl, BorderLayout.SOUTH);
//
mainPnl.add(topPnl, BorderLayout.NORTH);
// add(midPNL, BorderLayout.CENTER);
mainPnl.add(btmPnl, BorderLayout.CENTER);
add(mainPnl);
// Menu bar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Game");
menuBar.add(menu);
JMenuItem item3 = new JMenuItem("Change Name");
item3.addActionListener(this);
menu.add(item3);
JMenuItem item = new JMenuItem("Change Card Deck");
item.addActionListener(this);
menu.add(item);
JMenu subMenu = new JMenu("Change BackGround");
subMenu.addActionListener(this);
menu.add(subMenu);
JMenuItem subItem = new JMenuItem("Blue");
subItem.addActionListener(this);
subMenu.add(subItem);
JMenuItem subItem2 = new JMenuItem("Green");
subItem2.addActionListener(this);
subMenu.add(subItem2);
//
menu.addSeparator();
//
JMenuItem item4 = new JMenuItem("Quit");
item4.addActionListener(this);
menu.add(item4);
setJMenuBar(menuBar);
} //End of GameFrame
public void setCard() {
GenRandom g1 = new GenRandom();
g1.GenRandomCard();
int[] allCard = new int[11];
allCard = g1.getAllCard();
for (int i = 1; i <= 10; i++) {
card[i] = "image/card/" + allCard[i] + ".png";
}
}
public void setName() {
// name = JOptionPane.showInputDialog(null, "Please Enter Your Name", "Welcome", JOptionPane.QUESTION_MESSAGE) + ":";
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == card1Btn) {
playerBtn.setIcon(card1Pic);
card1Btn.setEnabled(false);
}
if (e.getSource() == card2Btn) {
playerBtn.setIcon(card2Pic);
card2Btn.setEnabled(false);
}
if (e.getSource() == card3Btn) {
playerBtn.setIcon(card3Pic);
card3Btn.setEnabled(false);
}
if (e.getSource() == card4Btn) {
playerBtn.setIcon(card4Pic);
card4Btn.setEnabled(false);
}
if (e.getSource() == card5Btn) {
playerBtn.setIcon(card5Pic);
card5Btn.setEnabled(false);
}
if (e.getSource() == restartBtn) {
new AePlayWave("sound/jet.wav").start();
JOptionPane.showMessageDialog(null, "Restart Button ");
}
if (e.getSource() == exitBtn) {
/* long start = System.currentTimeMillis();
long end = start + 4 * 1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end) {
// run
new AePlayWave("sound/jet.wav").start();
}*/
System.exit(0);
}
}
}
Since you did not post an SSCCE, I will do it for you. This shows how to change the background color of a JFrame. Starting from this, you can start adding components to the JFrame and see where you go wrong, instead of letting us look at a few hundred lines of code.
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.EventQueue;
public class ColoredFrame {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
frame.getContentPane().setBackground( Color.PINK );
//frame contains nothing, so set size
frame.setSize( 200, 200 );
frame.setVisible( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} );
}
}
Just put your setVisible(true); at the end of your constructor.
Moreover you had added mainPnl on your JFrame, so changing colour of the JFrame will be useless,
so instead of writing
add(mainPnl);
in your GameFrame class, you better be using
setContentPane(mainPnl);
for frame1.getContentPane().setBackground(Color.YELLOW); to work.
Hope this might help
Regards
You should give background color to JPanel and then use this JPanel in your JFrame rather than giving direct background to your JFrame.
I know this is a very old question, but for others that are looking for the right answer this could also be written as following:
frame1.getContentPane().setBackground(new Color (255,255,102)); //or whatever color you want in the RGB range