GameHutSoftware wrote:
16Skittles wrote:
GameHutSoftware wrote:
there isnt any source to put up yet
and yes im using swing (i think)Well of course there is a source code... Otherwise you would have nothing! Your .java files are what I'm talking about.
i do have nothing
Oh, lol.
Offline
my source:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* GUI.java
*
* Created on Feb 5, 2012, 8:08:04 PM
*/
/**
*
* @author Alex
*/
public class GUI extends javax.swing.JFrame {
/** Creates new form GUI */
public GUI() {
initComponents();
}
String whatThereWas = "";
String status = "intro";
String yourAnswer;
Boolean acceptingInput = false;
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
input = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
output = new javax.swing.JScrollPane();
outputText = new javax.swing.JTextArea();
jLabel1.setText("jLabel1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
outputText.setColumns(20);
outputText.setRows(5);
outputText.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
outputTextMouseMoved(evt);
}
});
output.setViewportView(outputText);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(79, 79, 79))
.addComponent(output, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
.addComponent(input, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(output, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(input, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void outputTextMouseMoved(java.awt.event.MouseEvent evt) {
outputText.setText("Welcome to THE AVATURIA SAGA!\nMake sure to save before closing! It won't remind you!\nWhen selecting something, possible choices appear in brackets.\n\nDo you have a saved game, or would you like to create a new one?(new, saved)");
acceptingInput = true;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField input;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane output;
private javax.swing.JTextArea outputText;
// End of variables declaration
}Offline
my response to that code: o_o
Sorry, but I won't be of much help.
Offline
16Skittles wrote:
my response to that code: o_o
Sorry, but I won't be of much help.![]()
i just need to know how to do the enter thing
netbeans spawned most of that code for me
Offline
I don't know about using enter, but if it's okay I changed it so that there is a button titled "submit" that will set the text to a string (currently titled fixSkittles) and will then reset the text box. Search for fixSkittles and you'll find all instances to change whatever you want.
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* GUI.java
*
* Created on Feb 5, 2012, 8:08:04 PM
*/
/**
*
* @author Alex
*/
public class GUI extends javax.swing.JFrame {
/** Creates new form GUI */
public GUI() {
initComponents();
}
String whatThereWas = "";
String status = "intro";
String yourAnswer;
Boolean acceptingInput = false;
String fixSkittles;
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
input = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
output = new javax.swing.JScrollPane();
outputText = new javax.swing.JTextArea();
jLabel1.setText("jLabel1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
outputText.setColumns(20);
outputText.setRows(5);
outputText.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
outputTextMouseMoved(evt);
}
});
output.setViewportView(outputText);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fixSkittles = input.getText();
outputText.setText("You said " + fixSkittles + "!");
input.setText("");
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(output, GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addComponent(input, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
.addComponent(jButton1))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnSubmit)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(output, GroupLayout.PREFERRED_SIZE, 185, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 0, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(input, GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
.addComponent(btnSubmit))
.addContainerGap())
);
getContentPane().setLayout(layout);
pack();
}// </editor-fold>
private void outputTextMouseMoved(java.awt.event.MouseEvent evt) {
outputText.setText("Welcome to THE AVATURIA SAGA!\nMake sure to save before closing! It won't remind you!\nWhen selecting something, possible choices appear in brackets.\n\nDo you have a saved game, or would you like to create a new one?(new, saved)");
acceptingInput = true;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField input;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane output;
private javax.swing.JTextArea outputText;
}Offline
I love some good coffee.
Offline
soupoftomato wrote:
I love some good coffee.
PLEASE don't start this again! We already had to have a moderator remove all of those "coffee" posts because they were off topic and obvious trolls.
Offline
GameHutSoftware wrote:
16Skittles wrote:
my response to that code: o_o
Sorry, but I won't be of much help.![]()
i just need to know how to do the enter thing
netbeans spawned most of that code for me
Well I don't know anything about JFrame, but could you try searching for a \n character every keypress and, if one is found, storing the user input box in a string variable, erasing the text box, and then writing the variable to another box?
Offline
Mokat wrote:
I am at school now typing this (comp lab) abd its sooooo annoying i cant watch anything cuz the school computers dont have java
![]()
download while their not looking
its free and easy
here
Offline
Here's a little project I've been working on. It's a Bukkit plugin, and I think it's epic.
Message.java
package geeksonaplane.SlimChat;
import org.bukkit.entity.Player;
public class Message {
String m;
Player p;
long t;
public Message(Player player, String message, long time) {
p = player; m = message; t = time;
}
public long getTime(){
return t;
}
public long getTimeElapsed(long l) {
return l - t;
}
public Player getPlayer(){
return p;
}
public String getMessage(){
return m;
}
}SlimChat.java
package geeksonaplane.SlimChat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public class SlimChat extends JavaPlugin implements Listener{
public static Map<String, String> PlayerChannel = new HashMap<String, String>();
public static Map<Player, Integer> Offenses = new HashMap<Player, Integer>();
public static boolean shout = false;
public static boolean whisper = false;
public static List<String> Channels = new ArrayList<String>();
public static List<Message> messages = new ArrayList<Message>();
Logger log = Logger.getLogger("Minecraft");
Listener listener;
public static FileConfiguration config;
private static String ListToString(List<String> list, int offset, String itemcolor, String commacolor){
StringBuffer buffer = new StringBuffer();
buffer.append("§");
buffer.append(itemcolor);
buffer.append(list.get(0));
for(int x = offset+1;x<list.size(); x++){
buffer.append("§");
buffer.append(commacolor);
buffer.append(", ");
buffer.append("§");
buffer.append(itemcolor);
buffer.append(list.get(x));
}
return buffer.toString();
}
@Override
public void onDisable() {
log.info("Plugin Disabled!");
}
@Override
public void onEnable() {
log.info("[SlimChat]Plugin Enabled!");
listener = new SlimChatListener(this);
Channels.add("global");
Channels.add("all");
getDataFolder().mkdirs();
config = getConfig();
config.addDefault("replaceunderscore", true);
config.addDefault("timebetweendifferentmessages", 5);
config.addDefault("timebetweenidenticalmessages", 10);
config.options().copyDefaults(true);
saveConfig();
if(!Bukkit.getPluginManager().isPluginEnabled("PermissionsEx")){
log.severe("PermissionsEx not found! Using default names and no prefixes.");
}
}
public boolean onCommand(CommandSender s, Command c, String l, String[] args){
if(l.equalsIgnoreCase("ch")){
if(args.length == 2){
if(!s.hasPermission("slimchat.channels.manipulate")){
s.sendMessage("§cYou do not have permission to manipulate channels.");
return true;
}
if(args[0].equalsIgnoreCase("create")){
if(Channels.contains(args[1].toLowerCase())){
s.sendMessage("§cThat channel already exists!");
return false;
}else{
Channels.add(args[1].toLowerCase());
s.sendMessage("§aChannel §f"+args[1]+"§a successfully created.");
return true;
}
}
if(args[0].equalsIgnoreCase("remove")) {
if(Channels.contains(args[1].toLowerCase())){
Channels.remove(args[1].toLowerCase());
for(int x = 0; x<Bukkit.getOnlinePlayers().length; x++){
if(PlayerChannel.get(Bukkit.getOnlinePlayers()[x]) == args[1].toLowerCase()){
PlayerChannel.remove(Bukkit.getOnlinePlayers()[x]);
}
}
s.sendMessage("§aChannel §f"+args[1]+"§a successfully removed.");
return true;
}else{
s.sendMessage("§cThat channel does not exist!");
return false;
}
}
}
if(args.length == 1){
if(!s.hasPermission("slimchat.channels.change")){
s.sendMessage("§cYou do not have permission to change your channel.");
return true;
}
if(args[0].equalsIgnoreCase("get")){
s.sendMessage("§aChannels: "+ListToString(Channels, 0, "f", "a"));
return true;
}else if(args[0].equalsIgnoreCase("all")){
if(s.hasPermission("slimchat.channels.all")){
PlayerChannel.put(s.getName(), "all");
s.sendMessage("§aYour channel has been set to §f"+args[0]+"§a.");
return true;
}else{
s.sendMessage("§cYou do not have permission to monitor all channels.");
return true;
}
}else if(args[0].equalsIgnoreCase("global")) {
PlayerChannel.remove(s.getName());
s.sendMessage("§aYour channel has been set to §f"+args[0]+"§a.");
return true;
}else{
if(Channels.contains(args[0])) {
PlayerChannel.put(s.getName(), args[0].toLowerCase());
s.sendMessage("§aYour channel has been set to §f"+args[0]+"§a.");
return true;
}else{
s.sendMessage("§cThat channel does not exist!");
return false;
}
}
}
}
if(l.equalsIgnoreCase("shout")){
if(s instanceof Player && !s.hasPermission("slimchat.shout")){
s.sendMessage("§cYou do not have permission to use shout.");
return true;
}
if(shout){
shout = false;
if(s instanceof Player) {
s.sendMessage("§cShout has been deactivated for all players.");
}else{
log.info("Shout has been deactivated for all players.");
}
return true;
}else{
whisper = false;
shout = true;
if(s instanceof Player) {
s.sendMessage("§aShout has been activated for all players.");
}else{
log.info("Shout has been activated for all players.");
}
return true;
}
}
if(l.equalsIgnoreCase("whisper")){
if(s instanceof Player && ! s.hasPermission("slimchat.whisper")) {
s.sendMessage("§cYou do not have permission to use whisper.");
return true;
}
if(whisper){
if(s instanceof Player) {
whisper = false;
s.sendMessage("§cWhisper has been deactivated for all players.");
}else{
whisper = false;
log.info("Whisper has been deactivated for all players.");
}
return true;
}else{
if(s instanceof Player) {
whisper = true;
shout = false;
s.sendMessage("§aWhisper has been activated for all players.");
}else{
log.info("Whisper has been activated for all players.");
whisper = true;
shout = false;
}
return true;
}
}
return false;
}
}SlimChatListener.java
package geeksonaplane.SlimChat;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
public class SlimChatListener implements Listener{
SlimChat plugin;
Logger log = Logger.getLogger("Minecraft");
public SlimChatListener(SlimChat instance) {
instance.getServer().getPluginManager().registerEvents(this, instance);
}
@EventHandler
public void onPlayerChat(PlayerChatEvent e){
Player p = e.getPlayer();
String pr;
String dn;
String sf;
String message;
String messagedraft;
boolean hassent = false;
Message m;
int index;
if(Bukkit.getPluginManager().isPluginEnabled("PermissionsEx")){
PermissionManager perm = PermissionsEx.getPermissionManager();
PermissionUser pu = perm.getUser(p);
pr = pu.getPrefix().replaceAll("_"," ").replaceAll("&", "§");
dn = pu.getName().replaceAll("_"," ").replaceAll("&", "§");
sf = pu.getSuffix().replaceAll("_"," ").replaceAll("&", "§");
if(pu.has("slimchat.color")) {
messagedraft = e.getMessage().replaceAll("&", "§");
}else{
messagedraft = e.getMessage();
}
}else{
pr="";
sf="";
dn = p.getName().replaceAll("_"," ");
if(p.hasPermission("slimchat.color")) {
messagedraft = e.getMessage().replaceAll("&","§");
}else{
messagedraft = e.getMessage();
}
}
if(SlimChat.shout) {
message = ("§c").concat(messagedraft.toUpperCase());
}else if (SlimChat.whisper){
message = ("§7").concat(messagedraft.toLowerCase());
}else{
message = messagedraft;
}
if(SlimChat.PlayerChannel.containsKey(p.getName()) && !(SlimChat.PlayerChannel.get(p.getName()) == "all")){
Player[] op = Bukkit.getOnlinePlayers();
for(int x = 0; x < op.length; x++){
if(SlimChat.PlayerChannel.containsKey(p.getName())){
if(SlimChat.PlayerChannel.get(op[x].getName()) == SlimChat.PlayerChannel.get(p.getName()) || SlimChat.PlayerChannel.get(op[x]) == "all"){
p.sendMessage("§e["+SlimChat.PlayerChannel.get(p.getName())+"]§f<"+pr+dn+sf+">"+message);
}
}
}
}else{
index = 0;
m = null;
for(int x = 0; x < SlimChat.messages.size(); x++){
if(SlimChat.messages.get(x).getPlayer() == p && !hassent){
m = SlimChat.messages.get(x);
index = x;
hassent = true;
}
}
if(hassent){
if(m.getMessage().toLowerCase() == message.toLowerCase()){
if((m.getTimeElapsed(System.currentTimeMillis())/1000) > SlimChat.config.getInt("timebetweenidenticalmessages")){
Bukkit.broadcastMessage("<"+pr+dn+sf+">"+message);
SlimChat.messages.remove(index);
SlimChat.messages.add(new Message(p, message, System.currentTimeMillis()));
}else{
p.sendMessage("§cYou must wait §f"+(SlimChat.config.getInt("timebetweenidenticalmessages")-(int)m.getTimeElapsed(System.currentTimeMillis())/1000)+" §cseconds before sending this message.");
if(!SlimChat.Offenses.containsKey(p)){
SlimChat.Offenses.put(p, 1);
}else{
SlimChat.Offenses.put(p, SlimChat.Offenses.get(p)+1);
}
if(SlimChat.Offenses.get(p) > 9){
SlimChat.Offenses.put(p, 0);
p.kickPlayer("You have been kicked for spamming. §khaxor");
}
}
}else{
if((m.getTimeElapsed(System.currentTimeMillis())/1000) > SlimChat.config.getInt("timebetweendifferentmessages")){
Bukkit.broadcastMessage("<"+pr+dn+sf+">"+message);
SlimChat.messages.remove(index);
SlimChat.messages.add(new Message(p, message, System.currentTimeMillis()));
}else{
p.sendMessage("§cYou must wait §f"+(SlimChat.config.getInt("timebetweendifferentmessages")-(int)m.getTimeElapsed(System.currentTimeMillis())/1000)+" §cseconds before sending this message.");
if(!SlimChat.Offenses.containsKey(p)){
SlimChat.Offenses.put(p, 1);
}else{
SlimChat.Offenses.put(p, SlimChat.Offenses.get(p)+1);
}
if(SlimChat.Offenses.get(p) > 9){
SlimChat.Offenses.put(p, 0);
p.kickPlayer("You have been kicked for spamming. §khaxor");
}
}
}
}else{
Bukkit.broadcastMessage("<"+pr+dn+sf+">"+message);
SlimChat.messages.add(new Message(p, message, System.currentTimeMillis()));
}
}
e.setCancelled(true);
}
}
Offline
GameHutSoftware wrote:
Mokat wrote:
I am at school now typing this (comp lab) abd its sooooo annoying i cant watch anything cuz the school computers dont have java
![]()
download while their not looking
its free and easy
here
most likely they don't have sufficient privileges to install.
@wmays what is slimchat for?
Offline
I am currently just starting off learning Java, but I'm kind of busy with school and sports, so the only thing I can really do right now is "Hello World". I use a program called Eclipse which is really good, you should check it out.
Offline
adriangl wrote:
I am currently just starting off learning Java, but I'm kind of busy with school and sports, so the only thing I can really do right now is "Hello World". I use a program called Eclipse which is really good, you should check it out.
i use eclipse too!
the latest project i've been working on is called "blockgen" a scratch project summary parser i'll try and post the source soon!
Offline
GameHutSoftware wrote:
Mokat wrote:
I am at school now typing this (comp lab) abd its sooooo annoying i cant watch anything cuz the school computers dont have java
![]()
download while their not looking
its free and easy
here
I couldn't. The way they have it, if your logged in as a student, they block websites like that so that you cant download java, firefox, google chrome, etc. by making this error message pop up: "Warning: the school district has blocked this download." and you cant get to the website.
Last edited by Mokat (2012-02-09 18:40:15)
Offline
The good: I'm now at tutorial 37 out of 87! (only) 50 more to go!
The bad: I'm getting really irritated by the complexness of displaying images... Does anyone know of a simple way to display images in a jPanel?
Offline
16Skittles wrote:
The good: I'm now at tutorial 37 out of 87! (only) 50 more to go!
![]()
The bad: I'm getting really irritated by the complexness of displaying images... Does anyone know of a simple way to display images in a jPanel?
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(AClassName.class
.getResource("path/to/image/relative/to/the/class/above"));
} catch (IOException ex) {
System.err.println("error finding image");
}
}
public ImagePanel(String path){
try {
// this.setOpaque(false);
image = ImageIO.read(new File(path));
} catch (IOException ex) {
System.err.println("error finding image");
}
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}Offline
TRocket wrote:
16Skittles wrote:
The good: I'm now at tutorial 37 out of 87! (only) 50 more to go!
![]()
The bad: I'm getting really irritated by the complexness of displaying images... Does anyone know of a simple way to display images in a jPanel?Code:
import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; public class ImagePanel extends JPanel { private BufferedImage image; public ImagePanel() { try { image = ImageIO.read(AClassName.class .getResource("path/to/image/relative/to/the/class/above")); } catch (IOException ex) { System.err.println("error finding image"); } } public ImagePanel(String path){ try { // this.setOpaque(false); image = ImageIO.read(new File(path)); } catch (IOException ex) { System.err.println("error finding image"); } } @Override public void paintComponent(Graphics g) { g.drawImage(image, 0, 0, null); } }
That's probably the simplest code for that I've seen, but can you help me understand a little more?
Sorry.
Offline
16Skittles wrote:
TRocket wrote:
16Skittles wrote:
The good: I'm now at tutorial 37 out of 87! (only) 50 more to go!
![]()
The bad: I'm getting really irritated by the complexness of displaying images... Does anyone know of a simple way to display images in a jPanel?Code:
import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; public class ImagePanel extends JPanel { private BufferedImage image; public ImagePanel() { try { image = ImageIO.read(AClassName.class .getResource("path/to/image/relative/to/the/class/above")); } catch (IOException ex) { System.err.println("error finding image"); } } public ImagePanel(String path){ try { // this.setOpaque(false); image = ImageIO.read(new File(path)); } catch (IOException ex) { System.err.println("error finding image"); } } @Override public void paintComponent(Graphics g) { g.drawImage(image, 0, 0, null); } }That's probably the simplest code for that I've seen, but can you help me understand a little more?
Sorry.
image = ImageIO.read(AClassName.class.getResource("path/to/image/relative/to/the/class/above"));in the constructor makes a Buffered image with the path you specify
@Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}simply overrides the JPanels paint method(called when the panel contents needs to be redrawn) and draws your image at 0,0
Offline
I need to make my own JPanel, right? I've done that, but how do I display the image? I made a separate class with main(String args[]) and I get the JFrame, but it doesn't display the image.
Offline
16Skittles wrote:
I need to make my own JPanel, right? I've done that, but how do I display the image? I made a separate class with main(String args[]) and I get the JFrame, but it doesn't display the image.
hmm
have you got
ImagePanel image = new ImagePanel();
jFrame.add(image)?
if it still doesn't work try
image.paint(jFrame.getGraphics());
after the panel is added and everything is visible
Offline
TRocket wrote:
16Skittles wrote:
I need to make my own JPanel, right? I've done that, but how do I display the image? I made a separate class with main(String args[]) and I get the JFrame, but it doesn't display the image.
hmm
have you gotCode:
ImagePanel image = new ImagePanel(); jFrame.add(image)?
if it still doesn't work tryCode:
image.paint(jFrame.getGraphics());after the panel is added and everything is visible
THANKYOUTHANKYOUTHANKYOU!!!!!
W00T! Now to start making some simple games...
Offline
16Skittles wrote:
TRocket wrote:
16Skittles wrote:
I need to make my own JPanel, right? I've done that, but how do I display the image? I made a separate class with main(String args[]) and I get the JFrame, but it doesn't display the image.
hmm
have you gotCode:
ImagePanel image = new ImagePanel(); jFrame.add(image)?
if it still doesn't work tryCode:
image.paint(jFrame.getGraphics());after the panel is added and everything is visible
THANKYOUTHANKYOUTHANKYOU!!!!!
W00T! Now to start making some simple games...
you're welcome
Offline
Can someone link me to a tutorial on using the Graphics and/or Graphics2D classes?
Offline
Alright! I've now modified your original code to become a main paint class, with a constructor for the image's x and y (lol fail I tried to spell out "why" there)
Edit: I've also managed to make an "animation!" Really it was just some scribbles in paint, but I made it go across the screen and discovered the JFrame.repaint() function.
Last edited by 16Skittles (2012-02-17 18:08:29)
Offline